简体   繁体   中英

Freemarker template loading

In my application, all freemarker templates are in /templates/ftl/ so during the application deployment I load a class I call one class that extends FreemarkerManager and has a method

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

In this way, when I need to load a template file, I can simply do it like this:

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

In only one specific situation, I need to get a template that comes from completely different path (not the /templates/ftl/).

How can I in this specific moment declare 2nd directory for template loading without breaking all the existing code that were calling the old path? Can I have 2 different starting point for template loading at the same time?

Thanks

You can use 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);

Source: Freemarker Manual

Another and a more elegant way (in my opinion) of doing this is within the config xml:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM