从类路径设置freemarker模板

36

我有一个Web应用程序,需要手动获取Freemarker模板 - 模板是通过库项目中的一个类获取的,但实际的tpl文件包含在Web应用程序类路径中。因此,有两个项目,一个是'taac-backend-api',另一个是'taac-web';taac-backend-api有代码来获取和处理模板,但模板存储在taac-web中(具体而言是在:WEB-INF/classes/email/vendor.tpl)- 我尝试使用从Spring的classpath资源到Freemarker的setClassForTemplateLoading方法等方法。 我认为这样做可以:

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

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

谢谢。

5个回答

86

以下是最终适用于我的解决方案:

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

请问 "email/vendor.tpl" 应该在哪里? - Salem loress

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中。


5
freemarkerConfiguration = new Configuration();
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("template.tpl");

使用此方法从包中加载类,其中包含您的类,因此如果您的类是org.foo.SomeClass,则将在类路径中查找/org/foo中的模板。这样可以将模板与使用/加载它们的类存储在一起。

1
但是如果我想将模板保留在“资源/模板”文件夹下,我该怎么做? - Aromal
@Aromal 找到解决方案了吗? - Ijaz

1
如果您正在使用Struts 2和Conventions插件,则wuntee的解决方案似乎不起作用:setClassForTemplateLoading会创建ClassTemplateLoader的实例,无论指定什么路径前缀,它都无法在jar文件中找到文件。
相反,创建StrutsClassTemplateLoader的实例。(我在FreemarkerManager的自定义子类中的getTemplateLoader方法中执行此操作。)它不需要任何参数,因此它只知道Struts和Conventions如何做事情。

根据类加载器层次结构,有时需要仔细考虑为ClassTemplateLoader指定哪个类。通常最好使用直接接受ClassLoader(而不是Class - 自2.3.22以来)的ClassTemplateLoader构造函数,然后将Web应用程序的线程上下文类加载器传递进去。 - ddekany

1

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

spring.freemarker.template-loader-path=

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接