简体   繁体   中英

Java Spring Freemarker internationalization for templates

I am trying to do internationalization for my templates but i'm not sure if it's most efficient way to do it like this.

I extracted messages to resource bundle and i use MessageSource method getMessage(String var1, @Nullable Object[] var2, Locale var3) to get translation based on Locale, then i put it into model and process the template.

private String processTemplate(String templateName, String locale) {
    try {
      String greeting = messageSource.getMessage("messages.greeting", null, new Locale(locale));
      Map<String, String> model = new HashMap<>();
      model.put("greeting", greeting);
      Template template = freemarkerConfiguration.getConfiguration().getTemplate(templateName);
      return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
      log.error("Error when processing template {}", templateName);
      throw new EmailNotSentException();
    }
  }

My question is if there is more efficient way to process template in this manner ? Or it would be better to have internatiolization for templates ?

It depends. If you use those templates as your main ui renderers, internationalize the message is the better option. But if those templates are for "emailing" I'll opt for their internationalization. In my application I have a similar use case, and I defined my templates like:

order-template-fr.ftl , order-template-es.ftl , order-template-en.ftl , ...

I resolve the template at runtime basing on the user's locale, using LOCALE_CONTRY.toLowerCase() . Example:

String template = "order-template-"+LOCALE_CONTRY.toLowerCase()+".ftl";

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