Подтвердить что ты не робот

Интернационализация электронной почты с использованием шаблонов Velocity/FreeMarker

Как я могу достичь i18n с помощью механизма шаблонов, такого как Velocity или FreeMarker, для построения тела электронной почты?

Обычно люди склонны создавать шаблоны, например:

<h3>${message.hi} ${user.userName}, ${message.welcome}</h3>
<div>
   ${message.link}<a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.
</div>

И у вас есть ресурсный пакет, созданный с такими свойствами, как:

message.hi=Hi
message.welcome=Welcome to Spring!
message.link=Click here to send email.

Это создает одну основную проблему: если мои файлы .vm становятся большими со многими строками текста, становится утомительно переводить и управлять каждым из них в отдельных файлах ресурсов (.properties).

То, что я пытаюсь сделать, это создать отдельный файл .vm, созданный для каждого языка, что-то вроде mytemplate_en_gb.vm, mytemplate_fr_fr.vm, mytemplate_de_de.vm, а затем как-то сказать Velocity/Spring выбрать правильный, основанный на вводе Locale.

Возможно ли это в Spring? Или я должен смотреть на, возможно, более простые и очевидные альтернативные подходы?

Примечание. Я уже видел Spring учебник о том, как создавать тела электронной почты с использованием шаблонов. Но, похоже, он не отвечает на мой вопрос по i18n.

4b9b3361

Ответ 1

Получается, что один шаблон и несколько файлов language.properties выигрывают за несколько шаблонов.

Это создает одну основную проблему: если мои .vm файлы становятся большими с много строк текста, становится утомительно переводить и управлять каждым из их в отдельных файлах ресурсов (.properties).

Еще сложнее поддерживать, если ваша структура электронной почты дублируется в нескольких файлах .vm. Кроме того, нужно будет вновь изобрести механизм спада ресурсов. Пакеты ресурсов пытаются найти ближайшее совпадение с учетом локали. Например, если locale en_GB, он пытается найти нижеприведенные файлы по порядку, возвращаясь к последнему, если ни один из них не доступен.

  • language_en_GB.properties
  • language_en.properties
  • language.properties

Я напишу (подробно), что мне нужно было сделать, чтобы упростить чтение пакетов ресурсов в шаблонах Velocity.

Доступ к набору ресурсов в шаблоне скорости

Spring Конфигурация

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="content/language" />
</bean>

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">    
    <property name="resourceLoaderPath" value="/WEB-INF/template/" />
    <property name="velocityProperties">
        <map>
            <entry key="velocimacro.library" value="/path/to/macro.vm" />
        </map>
    </property>
</bean>

<bean id="templateHelper" class="com.foo.template.TemplateHelper">
    <property name="velocityEngine" ref="velocityEngine" />
    <property name="messageSource" ref="messageSource" />
</bean>

Класс шаблонаHelper

public class TemplateHelper {
    private static final XLogger logger = XLoggerFactory.getXLogger(TemplateHelper.class);
    private MessageSource messageSource;
    private VelocityEngine velocityEngine;

    public String merge(String templateLocation, Map<String, Object> data, Locale locale) {
        logger.entry(templateLocation, data, locale);

        if (data == null) {
            data = new HashMap<String, Object>();
        }

        if (!data.containsKey("messages")) {
            data.put("messages", this.messageSource);
        }

        if (!data.containsKey("locale")) {
            data.put("locale", locale);
        }

        String text =
            VelocityEngineUtils.mergeTemplateIntoString(this.velocityEngine,
                templateLocation, data);

        logger.exit(text);

        return text;
    }
}

Шаблон скорости

#parse("init.vm")
#msg("email.hello") ${user} / $user,
#msgArgs("email.message", [${emailId}]).
<h1>#msg("email.heading")</h1>

Мне пришлось создать макрос коротких рук, msg, чтобы читать из пакетов сообщений. Это выглядит так:

#**
 * msg
 *
 * Shorthand macro to retrieve locale sensitive message from language.properties
 *#
#macro(msg $key)
$messages.getMessage($key,null,$locale)
#end

#macro(msgArgs $key, $args)
$messages.getMessage($key,$args.toArray(),$locale)
#end

Пакет ресурсов

email.hello=Hello
email.heading=This is a localised message
email.message=your email id : {0} got updated in our system.

Использование

Map<String, Object> data = new HashMap<String, Object>();
data.put("user", "Adarsh");
data.put("emailId", "[email protected]");

String body = templateHelper.merge("send-email.vm", data, locale);

Ответ 2

Здесь решение (один шаблон, несколько файлов ресурсов) для Freemarker.

основная программа

// 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<String, Object> model = new HashMap<String, Object>();
// 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

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

${msg("subject.title")}