我在路径TemplateLoader
中有我的src/main/java
类
我的模板文件位于src/resources/template
当我尝试使用以下代码加载模板时
Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
config.setClassForTemplateLoading(this.getClass(), "/");
Template template = config.getTemplate( "resources/template/test.ftl");
它给出以下错误:
freemarker.template.TemplateNotFoundException:找不到以下模板
名称为“ resources / template / test.ftl”。
该文件位于正确的位置。那么,如何使用免费标记加载此文件?
最佳答案
问题是resources
仅存在于您的源代码中(这是Maven的事情),而不存在于已编译的项目中。因此它应该是config.getTemplate( "template/test.ftl");
。但是,如果先使用config.setClassForTemplateLoading(this.getClass(), "/template");
,然后使用config.getTemplate( "test.ftl");
,那就更好了。拥有模板根目录的目的是使实际位置透明,并防止模板包含的安全问题,从而公开不是模板的任意资源。