当前位置: 首页 > 知识库问答 >
问题:

Freemarker模板加载

岳浩
2023-03-14

在我的应用程序中,所有freemarker模板都位于/templates/ftl/中,因此在应用程序部署期间,我加载了一个类,我调用了一个扩展FreemarkerManager并具有方法的类

Configuration configuration = super.createConfiguration(servletContext);
configuration.setDirectoryForTemplateLoading(new File("/templates/ftl/"));

这样,当我需要加载模板文件时,我可以这样做:

    ServletContext servletContext = ServletActionContext.getServletContext();
    Configuration configFreemarker = (Configuration) servletContext
                    .getAttribute("freemarker.Configuration");
    Template template = configFreemarker.getTemplate("pathToMyTemplate");

仅在一种特定情况下,我需要获得一个来自完全不同路径的模板(而不是/templates/ftl/)。

如何在这个特定的时刻声明模板加载的第二个目录,而不破坏所有调用旧路径的现有代码?我可以同时有两个不同的模板加载起点吗?

谢啦

共有2个答案

法烨烨
2023-03-14

另一种更优雅的方法(在我看来)是在配置xml中:

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  <property name="templateLoaderPaths">
        <value>/path1/ , /path2/</value>
  </property>
</bean>
沙宣
2023-03-14

您可以使用MultipleTemplateLoader

import freemarker.cache.*; // template loaders live in this package

...

FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates"));
FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates"));
ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ftl2, ctl };
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);

cfg.setTemplateLoader(mtl);

资料来源:Freemarker手册

 类似资料:
  • 我正在尝试使用从多个位置加载模板。这个项目是使用开发的。 我有两个maven项目: > 我的网站:maven的主要项目,包含自定义模板,例如WEB-INF/ftl/landing/login。ftl 通用模板:包含位于WEB-INF/ftl的通用freemarker模板,例如WEB-INF/ftl/landing/login。ftl 例如,Freemarker的想法是在“我的网站”中搜索登陆/登录

  • 当我点击登录按钮并通过数据库成功登录后,它被重定向到hello.ftl页面。但是ftl页面显示此错误 FreeMarker模板错误(调试模式;在生产中使用RETHROW!):以下内容的计算结果为null或missing:==>var[在模板“hello.ftl”第8行,第32列]----提示:如果已知失败的表达式在法律上引用了有时为null或missing的内容,可以指定默认值,如myoption

  • 我对使用Dropwizard和Freemarker模板非常陌生。我正在尝试加载免费标记模板。但是,图像不会加载到正在显示的页面中 我使用html的标准img标记来显示图像 这些图像在jar文件中可用。 以下是该项目的结构 src |-main |--resources |--media |--images |--mload。巴布亚新几内亚 请让我知道如果我错过了任何显示图像

  • 问题内容: 加载freemarker模板时,我得到一个文件未找到异常,即使该模板实际上存在于路径中。 更新:它正在作为Web服务运行。它将基于搜索查询将xml返回给客户端。当我从另一个Java程序(从静态main)调用模板时,模板成功加载。但是当客户端请求xml时,发生FileNotFoundException。 操作系统:Windows 7文件的绝对路径:C:/ Users / Jay / wo

  • 我的文件在src/main/Resources/freemarker/email_notification.txt 我无法读取freemaker文件,即电子邮件通知。txt,其中包含html文件。 我的推荐信来自这里:http://websystique.com/spring/spring-4-email-using-velocity-freemaker-template-library/ 我尝试

  • 我使用Spring Initilizr创建了一个Spring启动应用程序。然后我加入了Apache的Freemarker模板引擎,从我的项目中加载模板。默认情况下,引擎从以下文件夹加载模板:文件夹。 我正在尝试加载一个简单的用户访问网页时作为模板的文件。但是我需要从文件夹加载模板。每当我尝试从文件夹外部加载模板时,模板引擎都无法找到模板。 我已经阅读了各种教程和堆栈溢出问题。没有人回答我的问题,我