java 在 .jar 中加载 freemarker 模板文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14753125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading freemarker templates folder inside .jar
提问by Gleeb
I am using freemarker templates in my application
我在我的应用程序中使用了 freemarker 模板
Before deploying my application to a jar file, all I needed to do in order to load my templates was this: cfg.setDirectoryForTemplateLoading(new File("templates"));
在将我的应用程序部署到 jar 文件之前,为了加载我的模板,我需要做的就是: cfg.setDirectoryForTemplateLoading(new File("templates"));
Which loaded all templates from the template folder I created inside my project.
它从我在项目中创建的模板文件夹中加载了所有模板。
Now, after moving to maven and deploying my application to an executable jar. The application cannot find this folder anymore (I have checked inside the .jar file and the "templates" folder is deployed right in the root directory)
现在,在转移到 maven 并将我的应用程序部署到一个可执行的 jar 之后。应用程序再也找不到这个文件夹(我已经检查了 .jar 文件,并且“templates”文件夹部署在根目录中)
I have tried everything I know, but with no luck.
我已经尝试了我所知道的一切,但没有运气。
How exactly am I supposed to load all my templates now? (I assume that if I put the folder outside the .jar file but in the same directory it will work. but that's not what i want.)
我现在应该如何加载所有模板?(我假设如果我将文件夹放在 .jar 文件之外但在同一目录中,它会起作用。但这不是我想要的。)
Thanks.
谢谢。
回答by Werner Kvalem Vester?s
Have a look at
看一下
void setClassForTemplateLoading(Class cl, String prefix);
...in the FreeMarker manual chapter about template loading.
...在有关模板加载的FreeMarker 手册章节中。
Example:
例子:
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
...if your templates is located in the templates
package relative to the root of the current class.
...如果您的模板位于templates
相对于当前类的根的包中。
回答by Shiv
Configuration cfg;
private Template template;
{
cfg=new Configuration();
try {
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
template = cfg.getTemplate("template.ftl");
}
This worked perfectly for me. Here my templates folder contains template.ftl which is under src/main/resources package.
这对我来说非常有效。这里我的模板文件夹包含在 src/main/resources 包下的 template.ftl。
回答by LOAS
An alternative to the mentioned
提到的替代方案
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
is
是
TemplateLoader ldr = new ClassTemplateLoader(classLoader, basePackagePath);
cfg.setTemplateLoader(ldr);
which can be useful if you need to load stuff from other jars than the one your ftl processor belongs to.
如果您需要从 ftl 处理器所属的 jar 之外的其他 jar 加载内容,这会很有用。
Calls to cfg.getTemplate(..)
will then perhaps be more convenient as they only need the path to the ftl relative to basePackagePath
cfg.getTemplate(..)
然后调用可能会更方便,因为它们只需要相对于 ftl 的路径basePackagePath