在.jar中加载freemarker模板文件夹

Gle*_*eeb 18 java freemarker maven

我在我的应用程序中使用freemarker模板

在将我的应用程序部署到jar文件之前,我需要做的就是加载我的模板: cfg.setDirectoryForTemplateLoading(new File("templates"));

其中加载了我在项目中创建的模板文件夹中的所有模板.

现在,在转移到maven并将我的应用程序部署到可执行jar之后.应用程序无法再找到此文件夹(我已在.jar文件中检查,并且"templates"文件夹已部署在根目录中)

我已经尝试过我所知道的一切,但没有运气.

我现在应该如何加载我的所有模板?(我假设如果我将文件夹放在.jar文件之外但在同一目录中它将起作用.但这不是我想要的.)

谢谢.

Wer*_*rås 27

看一下

void setClassForTemplateLoading(Class cl, String prefix);
Run Code Online (Sandbox Code Playgroud)

...在FreeMarker手册中有关模板加载的章节.

例:

cfg.setClassForTemplateLoading(this.getClass(), "/templates");
Run Code Online (Sandbox Code Playgroud)

...如果您的模板位于templates相对于当前类的根的包中.


小智 5

Configuration cfg;
private Template template;  
    {
        cfg=new Configuration(); 
        try {
            cfg.setClassForTemplateLoading(this.getClass(), "/templates");
            template = cfg.getTemplate("template.ftl");
}
Run Code Online (Sandbox Code Playgroud)

这对我来说非常有效。这里我的模板文件夹包含 template.ftl ,它位于 src/main/resources 包下。