Reputation: 8808
I have email template .vm which contains msg with message key from messages_en.properties:
#msg("email-body")
messages_en.properties has:
email-body = Hello, $name!
After:
private String buildMessage(String templateName, Properties properties, Locale locale) {
Template template = getVelocityEngine().getTemplate(templateName);
VelocityContext context = new VelocityContext();
for (String key : properties.stringPropertyNames()) {
context.put(key, properties.getProperty(key));
}
context.put(LocaleDirective.MESSAGES_LOCALE, locale);
StringWriter writer = new StringWriter();
template.merge(context, writer);
return writer.toString();
}
I get:
Hello, $name!
And name isn't replaced with actual value.
What's the best way to manage phrases in email template? I want to put only message key in the template, not the whole phrase with placeholder.
Upvotes: 0
Views: 1185
Reputation: 9961
Use evaluate directive for substitute variable inside of other variable:
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import java.io.StringReader;
import java.io.StringWriter;
public class Main {
public static void main(String[] args) throws Exception {
RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
StringReader reader = new StringReader("#evaluate($email-body)");
SimpleNode node = runtimeServices.parse(reader, "default");
Template template = new Template();
template.setRuntimeServices(runtimeServices);
template.setData(node);
template.initDocument();
VelocityContext context = new VelocityContext();
context.put("name", "Maxim");
context.put("email-body", "Hello, $name!");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
Output:
Hello, Maxim!
Upvotes: 1