API / Apache FreeMarker Interview questions
How do you use a custom TemplateTransformModel to post-process a template's output?
freemarker.template.TemplateTransformModel is an older, lower-level extension point that lets Java code intercept and rewrite whatever markup a block of template body produces, before it reaches the real output stream. Its single method, getWriter(Writer out, Map args), returns a custom Writer that the body writes into instead of writing directly to out.
public class CompressWhitespaceTransform implements TemplateTransformModel { public Writer getWriter(final Writer out, Map args) { return new StringWriter() { public void close() throws IOException { out.write(toString().replaceAll("\\s+", " ").trim()); } }; } }
Registered as a shared variable and used as <@compress> a lot of whitespace here </@compress>, it lets the body's raw output be captured, transformed, and only then written to the real destination.
In current FreeMarker code, a custom TemplateDirectiveModel generally covers the same need with a cleaner, more capable API, so TemplateTransformModel mostly shows up in older codebases; interview questions about it usually test whether the difference between "wrapping the output writer" and "controlling execution via a directive" is understood, more than expecting it to be used in new code.
More Related questions...