hrishikeshp19
hrishikeshp19

Reputation: 9028

freemarker configuration get template by locale and template name

My EmailHandler class is as follows:

Class EmailHandler {
    ...
    @Autowired
        protected Configuration config;
    }
    ...
    protected Template getTemplate(String templateName, Locale locale) throws IOException, TemplateException {
        return config.getTemplate(templateName, locale);
    }
    ...
}

In my applicationcontext.xml, I have

<bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
    <property name="templateLoaderPath" value="classpath:/templates/email"/>
</bean>

my directory structure for templates is as follows:

--src
----main
------resources
--------templates
----------email
------------template1.ftl
------------template2.ftl
------------template3.ftl
------------template4.ftl
------------multilanguage
--------------fr
----------------template1.ftl

At present getTemplate is always called with (string, Locale.US). But, in future, I want to be able to call getTemplate with (string, Locale.FR).

Following are my questions: 1. How should I change my directory structure to specify templates for french language. 2. What does config.getTemplate(templateName, locale); exactly do? How does that method find template for Locale.US in template directory? 3. I want to load my french language templates from email/multilanguage/fr directory. How do I do that?

Thanks,

Rishi

Upvotes: 3

Views: 8225

Answers (1)

ddekany
ddekany

Reputation: 31112

When you call getTemplate("foo.ftl", Locale.US), FreeMarker first tries to load foo_en_US.ftl, then foo_en.ftl, finally foo.ftl. So the French templates should be named like foo_fr.ftl.

The locale specified for getTemplate also decides what the value of the locale setting will be inside the template. This, however, can be overridden in the Environment object. That can be done if instead of myTemplate.process(...) you call env = myTemplate.createProcessingEnvironment(...); env.setLocale(...); env.process(), or in the template with <#setting locale='...'>.

As of loading templates from subdirectories based on the locale, you can implement a TemplateLookupStrategy for that (see http://freemarker.org/docs/api/freemarker/cache/TemplateLookupStrategy.html).

Upvotes: 10

Related Questions