我正在尝试对我的模板进行国际化,但我不确定这是否是最有效的方法。
我将消息提取到资源包中,并使用 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.ftl
、order-template-es.ftl
、order-template-en.ftl
、.. .
我使用 LOCALE_CONTRY.toLowerCase()
在运行时根据用户的区域设置解析模板。示例:
String template = "order-template-"+LOCALE_CONTRY.toLowerCase()+".ftl";
关于Java Spring Freemarker 模板国际化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767787/