How can I achieve i18n using a templating engine such as Velocity or FreeMarker for constructing email body?
Typically people tend to create templates like:
Here's the solution (one template, several resource files) for Freemarker.
the main program
// defined in the Spring configuration file
MessageSource messageSource;
Configuration config = new Configuration();
// ... additional config settings
// get the template (notice that there is no Locale involved here)
Template template = config.getTemplate(templateName);
Map model = new HashMap();
// the method called "msg" will be available inside the Freemarker template
// this is where the locale comes into play
model.put("msg", new MessageResolverMethod(messageSource, locale));
MessageResolverMethod class
private class MessageResolverMethod implements TemplateMethodModel {
private MessageSource messageSource;
private Locale locale;
public MessageResolverMethod(MessageSource messageSource, Locale locale) {
this.messageSource = messageSource;
this.locale = locale;
}
@Override
public Object exec(List arguments) throws TemplateModelException {
if (arguments.size() != 1) {
throw new TemplateModelException("Wrong number of arguments");
}
String code = (String) arguments.get(0);
if (code == null || code.isEmpty()) {
throw new TemplateModelException("Invalid code value '" + code + "'");
}
return messageSource.getMessage(code, null, locale);
}
}
Freemarker template
${msg("subject.title")}