Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 516
gospodin Avatar asked Oct 19 '25 14:10

gospodin


1 Answers

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

like image 197
Tom Verelst Avatar answered Oct 21 '25 04:10

Tom Verelst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!