【发布时间】:2021-05-18 08:25:27
【问题描述】:
我正在使用 Thymeleaf 发送电子邮件。我已经设置了我需要的模板,并且效果很好。我现在正尝试根据收件人的语言翻译这封电子邮件。我通过以前恢复的变量知道我需要使用的语言。 我正在使用属性文件来设置将被翻译的变量。 到目前为止,我掌握了三种语言:法语、英语和中文。所以我有三个属性文件:
- mail.messages_fr_FR
- mail.messages_zh_CN
- mail.messages_zh_CN
我的电子邮件配置类中有以下方法:
@Bean
public ReloadableResourceBundleMessageSource emailMessageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("mailMessages");
return messageSource;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
我已经启用了 Mvc:
@SpringBootApplication
@EnableWebMvc
public class AccessRequestEventHookApplication extends SpringBootServletInitializer implements WebMvcConfigurer {
我的电子邮件配置类中有一个方法如下:
public void sendMessageUsingThymeleafTemplate(String to, String subject, Map<String, Object> templateModel, String appName)
throws MessagingException {
Context thymeleafContext = new Context();
thymeleafContext.setVariables(templateModel);
String htmlBody;
if (appName == "Test1"){
htmlBody = thymeleafTemplateEngine.process("Test1-template", thymeleafContext);
} else {
htmlBody = thymeleafTemplateEngine.process("Test2-template", thymeleafContext);
}
sendHtmlMessage(to, subject, htmlBody);
}
然后在我的控制器中调用此函数。 我也有我的模板解析器和引擎如下:
@Bean
@Primary
public ITemplateResolver thymeleafTemplateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("mail-templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
@Bean
public SpringTemplateEngine thymeleafTemplateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.setTemplateEngineMessageSource(emailMessageSource());
return templateEngine;
}
我尝试用 cookie 更改语言环境解析器类型,acceptLanguage,它仍然不起作用。
如果我更改计算机上的语言(例如从法语到英语),它会起作用,使用英语翻译。但我不知道如何直接在代码中更改语言环境变量。 因为它是发送给用户的,所以我不能基于他们的语言环境。
如果我不清楚,请告诉我,我会提供任何需要的信息。
谢谢!
【问题讨论】:
-
如何触发 Thymeleaf 创建电子邮件 HTML?
标签: java email templates thymeleaf translation