|
Controlling WhitespaceThe control of the whitespace in a template is a problem that to some extent haunts every template engine in the business. In particular, the problem is that when using template code like this: <assign x="foo"> ${x} What you will get rendered is (below "[cr]" is used to denote newline characters):
It can be that you don't really want that newline to appear. Or, consider an even more drastic case: <foreach color in rainbow> ${color} </foreach> What you will get rendered is:
You can control this problem in two ways described below. 1. Using tag wrappingA FreeMarker tag can include whitespace. ANY whitespace. To eliminate the newline in the first above example, use: <assign x="foo" >${x} This yields:
With this syntax, we have effectively moved the undesired newline character
inside the <foreach color in rainbow >${color} </foreach> What you will get rendered is:
Of course, you can freely mix instructions, expressions and literal text on the same lines if that is what you'd like to have: Rainbow consists of <foreach color in rainbow><if !color_has_next> and </if>${color}<if color_has_next>, <else>.</if></foreach> 2. Using transformsFreeMarker supports custom transforms of the output using the
Note that you can use more advanced techniques as well: you can have a nicely formatted master copy of your templates that is meant for human editing, then as part of your build process you can derive another template that has all of its extraneous whitespace removed from it. While this technique yields best performance (as the whitespace removal is performed only once at build time, and not at run time) it falls outside the FreeMarker's scope. |
|