Collapsing whitespace in a Liquid template
Output an empty string with stripped whitespace, that is {{- "" -}}.
Here’s an excerpt from one of my Liquid templates:
<p class="title">
{{- article.title -}}
</p>
<p class="summary">
{{- article.summary | strip -}}
</p>
When this gets rendered, it inserts a space between the closing/opening <p> tags:
<p class="title">This is the title of the article</p>·<p class="summary">This is the summary of the article</p>
I don’t want the space in the final HTML – it’s unnecessary, and my current HTML minifier doesn’t optimise it away.
I could remove the space by modifying the template to remove the newlines between the </p> and <p class="summary">, but that would make the template more difficult to read. I recently thought of a better way to do it: insert an empty string between them, and use Liquid’s whitespace control to strip whitespace from both sides. Here’s the new template:
<p class="title">
{{- article.title -}}
</p>
{{- "" -}}
<p class="summary">
{{- article.summary | strip -}}
</p>
This renders the HTML without the unwanted space, and it keeps the template nice and readable. Other templating languages have similar syntax for inserting values and stripping whitespace, so I’m sure I could use this technique there as well.
This is a micro-optimisation that affects the size of the final page by maybe 0.1% – but it’s already aggressively optimised, so tiny wins like this are all I can do to keep the page size down.