Reduce whitespace in the source of Jekyll websites

Reduce whitespace in the source of Jekyll websites

A couple of days ago I noticed my websites source code had a lot of whitespace. Which in and of itself isn’t a big problem because the final page isn’t affected by it, but it’s a waste of space and bandwidth. The only question is what caused all this access whitespace…

This website is created with Jekyll, a simple static website generator. And Jekyll uses a system called liquid tags to define logic within the pages. These tags always render a newline even if the statement evaluates to false. So pages that rely heavily on logic, like my game collection, result in a lot of whitespace.

Here is a small example:

{% for Game in %}
{% if Game.Platform == "Nintendo Switch" %}
      <td>{{ Game.Title }}</td>
      <td>{{ Game.Genre }}</td>
      <td>{{ Game.Developer }}</td>
{% endif %}
{% endfor %}

Each game page iterates through all the games and checks if it should be displayed based on the platform. But because the way how liquid tags works every time a game doesn’t belong on the page a newline would be generated. A way to counteract this behaviour would be to replace {% and %} with {%- and -%} respectively.

This way liquid only renders the result of the statement. But beware don’t just replace everything automatically without checking every page on irregularities. Because sometimes your page or layout relies on these automatic newlines without you even knowing, especially if you use liquid tags to alter HTML tag attributes.