簡體   English   中英

模板的 Java Spring Freemarker 國際化

[英]Java Spring Freemarker internationalization for templates

我正在嘗試對我的模板進行國際化,但我不確定這樣做是否是最有效的方法。

我將消息提取到資源包,並使用 MessageSource 方法getMessage(String var1, @Nullable Object[] var2, Locale var3)獲取基於 Locale 的翻譯,然后將其放入模型並處理模板。

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";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM