从外部加载 Freemarker 模板 Url

Load Freemarker Template from External Url

我已经实现了 spring 启动应用程序,我们需要使用 freemarker 发送电子邮件。 应用程序将部署在 google 应用程序引擎上,其中的文件结构不可用于存储模板。因此,我将模板保存在具有 public 访问权限的 google 存储中。但是freemarker模板引擎无法加载

freeMarkerConfiguration.setDirectoryForTemplateLoading(new File("/home/dnilesh/Downloads/helloworld-springboot/src/main/resources/"));

content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
                freeMarkerConfiguration.getTemplate("Email.html"),model));

以上配置适用于开发环境。但是在 Google App Engine 上我没有存储模板的目录。

我试过了:

freeMarkerConfiguration.setDirectoryForTemplateLoading(new File("https://storage.googleapis.com/nixon-medical/"));

           content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
                    freeMarkerConfiguration.getTemplate("Email.html"),model));

但是 freemarker 没有从外部加载模板 URL。我该如何加载它?

对于外部 URL,您应该使用 URLTemplateLoader:

If your template source accesses the templates through an URL, you needn't implement a TemplateLoader from scratch; you can choose to subclass freemarker.cache.URLTemplateLoader instead and just implement the URL getURL(String templateName) method.

code sample

您可以使用 Thymeleaf 解析器加载外部文件。 https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html

虽然有一个可接受的答案,但我没有找到与 spring 引导的集成。所以我做了这个

我正在尝试使用 spring 启动应用程序从 google 云存储中读取 Freemarker 模板。

所以,我完成了以下操作并且对我有用。

  • 实现 URLTemplateLoader 并且只覆盖 getURL 方法 On
  • FreeMarkerConfigurer bean,将预模板设置为自定义模板

CloudTemplateLoader - 我的自定义加载器

public class CloudTemplateLoader extends URLTemplateLoader {
private URL root;
public CloudTemplateLoader(URL root) {
    super();
    this.root = root;
}

@Override
protected URL getURL(String template) {
    try {
        return new URL(root,  "/" + template);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}

}

FreeMarkerConfigurer Bean 来设置我的自定义加载器

@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() throws MalformedURLException {
    FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
    Properties properties = new Properties();
    properties.setProperty("localized_lookup", "false");
    freeMarkerConfigurer.setFreemarkerSettings(properties);
    freeMarkerConfigurer.setPreTemplateLoaders(new CloudTemplateLoader(new URL("https://storage.googleapis.com")));
    freeMarkerConfigurer.setDefaultEncoding("UTF-8");
    return freeMarkerConfigurer;
}

我的控制器正在关注

@GetMapping
public String index() {
    return "<bucket-name>/index.ftl";
}

不要忘记将模板上传到 google 云或 s3。出于测试目的,我在 index.ftl 文件上添加了 public 访问权限。