I create e-mails from templates via Velocity in a Spring Web Application. Now I need to HTML escape SOME of the values. I found the Velocity Escape Tool. But I did not get the configuration working.
What I have tryed so fare is (spring applicationContext.xml):
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="classpath:/velocity/emailTemplates" />
<property name="preferFileSystemAccess" value="false" />
<property name="overrideLogging" value="true" />
<property name="velocityProperties">
<util:properties>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="tools.toolbox">application</prop>
<prop key="tools.application.esc">org.apache.velocity.tools.generic.EscapeTool</prop>
</util:properties>
</property>
</bean>
Template (htmlEscapeTest.vm):
with escape: $esc.html($needEscape)
TestCase:
@Test
public void testHtmlEscapingSupport() {
final String needEscape = "<test>";
ModelMap model = new ModelMap();
model.addAttribute("needEscape", needEscape);
String result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HTML_ESCAPING_TEMPLATE_FILE, model);
assertThat(result, StringContains.containsString("<test>"));
}
But the Test failed, ...got: "with escape: $esc.html($needEscape)"
Can anybody give me a hint what I am doing wrong?
If I add new EscapeTool()
explicite in the test:
VelocityContext velocityContext = new VelocityContext(model);
velocityContext.put("esc", new EscapeTool());
StringWriter writer = new StringWriter();
velocityEngine.mergeTemplate(HTML_ESCAPING_TEMPLATE_FILE, velocityContext, writer);
String result = writer.toString();
then it is working. But as far as I understand the documentation, the tools should be configured once in the properties file.
I am using Velocity Engine 1.7 and Velocity Tools 2.0.