views:

329

answers:

2

Freemarker has the ability to do text escaping using something like this:

<#escape x as x?html>
Foo: ${someVal}
Bar: ${someOtherVal}
</#escape>

xml, xhtml, and html are all built in escapers. Is there a way to register a custom written escaper? I want to generate CSV and have each individual element escaped and that seems like a good mechanism.

I'm trying to do this in Struts 2 if that matters as well.

A: 

The Javadoc for HtmlEscaper indicates how to instantiate/register that in code (see the header), so I suspect if you implement your own TemplateTransformModel, and register it in a similar fashion then that should work.

Brian Agnew
I thought `<transform>` was deprecated?
ChssPly76
I don't know, I confess. Certainly the classes referenced don't appear to be
Brian Agnew
+1  A: 

You seem to be confusing two concepts here. ?xml, ?xhtml and ?html are string built-ins.
<#escape> OTOH is syntax sugar to save you from typing the same expression over and over again. It can be used with any expression, it's not limited to built-ins.

That said, there's unfortunately no built-in for csv string escaping and there's no way to write your own without modifying FreeMarker source (though if you do want to go this way it's pretty straightforward - take a look at freemarker.core.BuiltIn). Perhaps you can by with ?replace using regex or just write / expose an appropriate method and invoke it in your template.

ChssPly76
This answers the question. It looks like it's more trouble than it's worth. I think I'll go the CSVWriter route instead of a template.
geofflane