Java Spring Freemarker 模板国际化

标签 java spring internationalization freemarker

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

我将消息提取到资源包中,并使用 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 渲染器,则国际化消息是更好的选择。但如果这些模板用于“电子邮件”,我会选择它们的国际化。 在我的应用程序中,我有一个类似的用例,我定义了我的模板,例如:

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

我使用 LOCALE_CONTRY.toLowerCase() 在运行时根据用户的区域设置解析模板。示例:

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

关于Java Spring Freemarker 模板国际化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767787/

相关文章:

java - 如何使用非空字段实现 "complete later"功能?

php - 将xml数据写入oracle数据库

postgresql 中的 Postgresql 全文搜索 - 日语、中文、阿拉伯语

javascript - L20n.js : localize dynamically created strings

java - 有什么方法可以在java中传递带有2个输入参数的函数吗?

java - 如何在执行程序服务中使用数据排队

java - 无法通过 Java 主程序向队列发送消息

java - Spring+quartz 给出 java.lang.NoClassDefFoundError : weblogic/logging/LogEntryFormatter

java - 生产中的 VisualVM?

java - 使用 Java 读取 C 驱动器上每个文件的元数据和 MD5 哈希值