Email Internationalization using Velocity/FreeMarker Templates

后端 未结 2 1038
不思量自难忘°
不思量自难忘° 2021-01-30 13:51

How can I achieve i18n using a templating engine such as Velocity or FreeMarker for constructing email body?

Typically people tend to create templates like:



        
2条回答
  •  轮回少年
    2021-01-30 14:24

    Here's the solution (one template, several resource files) for Freemarker.

    the main program

    // defined in the Spring configuration file
    MessageSource messageSource;
    
    Configuration config = new Configuration();
    // ... additional config settings
    
    // get the template (notice that there is no Locale involved here)
    Template template = config.getTemplate(templateName);
    
    Map model = new HashMap();
    // the method called "msg" will be available inside the Freemarker template
    // this is where the locale comes into play 
    model.put("msg", new MessageResolverMethod(messageSource, locale));
    

    MessageResolverMethod class

    private class MessageResolverMethod implements TemplateMethodModel {
    
      private MessageSource messageSource;
      private Locale locale;
    
      public MessageResolverMethod(MessageSource messageSource, Locale locale) {
        this.messageSource = messageSource;
        this.locale = locale;
      }
    
      @Override
      public Object exec(List arguments) throws TemplateModelException {
        if (arguments.size() != 1) {
          throw new TemplateModelException("Wrong number of arguments");
        }
        String code = (String) arguments.get(0);
        if (code == null || code.isEmpty()) {
          throw new TemplateModelException("Invalid code value '" + code + "'");
        }
        return messageSource.getMessage(code, null, locale);
      }
    

    }

    Freemarker template

    ${msg("subject.title")}
    

提交回复
热议问题