Java Spring 模板的 Freemarker 国际化

Java Spring Freemarker internationalization for templates

我正在尝试对我的模板进行国际化,但我不确定这样做是否是最有效的方法。

我将消息提取到资源包中,并使用 MessageSource 方法 getMessage(String var1, @Nullable Object[] var2, Locale var3) 获取基于区域设置的翻译,然后我将其放入模型并处理模板。

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();
    }
  }

我的问题是是否有更有效的方法以这种方式处理模板?或者对模板进行国际化会更好?

视情况而定。如果您将这些模板用作主要 ui 呈现器,则将消息国际化是更好的选择。但是,如果这些模板适用于 "emailing",我会选择它们的国际化。 在我的应用程序中,我有一个类似的用例,我定义了我的模板:

order-template-fr.ftlorder-template-es.ftlorder-template-en.ftl、...

我在运行时根据用户的语言环境解析模板,使用LOCALE_CONTRY.toLowerCase()。示例:

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