从classpath设置freemarker模板

wun*_*tee 35 freemarker

我有一个Web应用程序,我需要手动获取Freemarker模板 - 模板是通过库项目中的类获得的,但实际的tpl文件包含在Web应用程序类路径中.因此,有2个项目,一个是"taac-backend-api",另一个是"taac-web"; taac-backend-api有代码来获取模板并对其进行处理,但是taac-web是模板存储的地方(具体在:WEB-INF/classes/email/vendor.tpl) - 我尝试过使用的所有内容使用Freemarkers setClassForTemplateLoading方法弹出classpath资源.我认为这会奏效:

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

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

谢谢.

wun*_*tee 80

这就是最终为我工作的东西:

freemarkerConfiguration = new Configuration(Configuration.VERSION_2_3_28);
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("email/vendor.tpl");
Run Code Online (Sandbox Code Playgroud)


Jan*_*nar 6

在2017年,不推荐使用以下内容:

Configuration conf = new Configuration();
Run Code Online (Sandbox Code Playgroud)

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

Configuration conf = new Configuration(new Version(2, 3, 23));
conf.setClassForTemplateLoading(Application.class, "/views");
Run Code Online (Sandbox Code Playgroud)

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

views目录位于中src/main/resources


use*_*048 5

freemarkerConfiguration = new Configuration();
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("template.tpl");
Run Code Online (Sandbox Code Playgroud)

使用此方法从您的类所在的包中加载类,因此如果您的类是

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