36

我有一个需要手动获取 Freemarker 模板的 Web 应用程序 - 模板是通过库项目中的类获得的,但实际的 tpl 文件包含在 Web 应用程序类路径中。因此,有 2 个项目,一个 'taac-backend-api' 和另一个 'taac-web';taac-backend-api 具有获取模板并对其进行处理的代码,但 taac-web 是存储模板的位置(特别是在:WEB-INF/classes/email/vendor.tpl) - 我已经尝试过使用弹簧类路径资源使用 Freemarkers setClassForTemplateLoading 方法。我认为这会起作用:

    freemarkerConfiguration = new Configuration();
    freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
    Template freemarkerTemplate = freemarkerConfiguration.getTemplate("/email/vendor.tpl");

然而,我总是得到一个 FileNotFoundException。有人可以解释从类路径获取模板的最佳方法吗?

谢谢。

4

5 回答 5

83

这就是最终为我工作的:

freemarkerConfiguration = new Configuration(Configuration.VERSION_2_3_28);
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("email/vendor.tpl");
于 2010-06-11T19:46:26.493 回答
11

2017 年,以下内容已弃用:

Configuration conf = new Configuration();

我们应该传递freemarker.template.Version给构造函数:

Configuration conf = new Configuration(new Version(2, 3, 23));
conf.setClassForTemplateLoading(Application.class, "/views");

其中版本号指的是 FreeMarker 的当前版本。

views目录位于src/main/resources.

于 2017-03-05T17:56:33.603 回答
4
freemarkerConfiguration = new Configuration();
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("template.tpl");

使用这个方法从你的类所在的包中加载类,所以如果你的类是

org.foo.SomeClass模板将/org/foo在类路径中查找。这使您的模板与使用/加载它们的类一起存储。

于 2013-10-16T15:35:11.033 回答
1

如果您使用的是 Struts 2 和 Conventions 插件,wuntee 的解决方案似乎不起作用:setClassForTemplateLoading反过来,ClassTemplateLoader无论指定什么路径前缀,都会创建一个在 jar 中找不到文件的实例。

相反,创建一个StrutsClassTemplateLoader. (我FreemarkerManager在其getTemplateLoader方法的自定义子类中执行此操作。)它不接受任何参数,所以大概它只知道 Struts 和 Conventions 是如何做事的。

于 2011-05-27T19:03:57.517 回答
0

使用以下配置并将其放在应用程序属性中。

spring.freemarker.template-loader-path=
于 2020-05-24T22:45:02.780 回答