Whitespace Control
If you’re doing web development and generating HTML, you normally don’t worry about whitespace. But there are other situations where it’s critical to control where whitespace – particularly linebreaks – occur.
At its defaults, Fluid only deals with bracketed elements. It either executes those expressions ({%..%}
) or replaces them with data {{..}}
. Anything outside of the tags is left alone.
This means that if you format your code using line breaks and indentation, that whitespace remains after the code is executed. We often create whitespace to help source code make sense. Imagine instantly removing all the tags from a template, and a lot of the whitespace just doesn’t make sense anymore.
Consider this template:
1.
2. {{ name }}
3.
1.
2. Deane
3.
That works fine, but imagine if we put a condition in there, and put them on their own lines for clarity:
1.
{% if name %}
2. {{ name }}
{% endif %}
3.
1.
2. Deane
3.
The conditionals are executed then removed, but the whitespace on the end of their lines – a line break in this case – is retained.
We can affect this by adding dashes just before the closing tags. This tells Fluid, “Trim from the end of this tag to the next non-whitespace character.”
1.
{% if name -%}
2. {{ name }}
{% endif -%}
3.
1.
2. Deane
3.
We can remove the whitespace from the beginning of the tags the same way, but it’s probably not what we want:
1.
{%- if name -%}
2. {{ name }}
{%- endif -%}
3.
1.
2.3. Deane4.
5.
It often takes some trial-and-error to figure out how you need to whitespace to layout.
If you don’t want this to be handled at the template level and want to globally control it, there’s a Trimming
property in TemplateOptions
:
TemplateOptions.Default.Trimming = TrimmingFlags.TagLeft | TrimmingFlags.TagRight;
If those flags are set, then it doesn’t matter what’s done at the template level – that setting will trim whitespace in all cases.