David Hutchison

Jekyll Generated HTML

I was debugging this site using the Chrome “Inspect Element” option (which is just amazing), and noticed the huge amount of whitespace that was in the HTML generated by Jekyll. Going by this bug report the engine is not smart enough to exclude whitespace between lines of code. I have seen extensions that claim to be able to solve this, but as I’m hosting on GitHub I need to keep to the standard install setup. I had a thought of how to solve this, and it works surprisingly well!

An updated solution is available.

The solution I’ve came to requires that the block of code that would cause all the newlines to be wrapped in a capture block, such as the example below.

{% capture input %}
{% include whitespace_generating_code %}
{% endcapture %}

The include file I created to do the trimming uses this “input” variable and replaces any occurrence of two newlines together with a single one. It recursively calls itself until the content going in matches the content after the replacement. At this point it outputs the result. I opted not to just remove the newlines because some will be legitimate. This does not handle lines that only contain spaces, but it is a good enough start at a solution.

To complete the example code would just require and extra include to be added after the “endcapture”.

{% capture input %}
{% include whitespace_generating_code %}
{% endcapture %}{% include trim %}

The code of the “trim” include is below. It has a very long line of code so it does not introduce it’s own newlines.

{% comment %}
Include that will use the supplied "input" variable and output it, minus duplicated newlines.
{% endcomment %}
{% capture nl2 %}

{% endcapture %}{% capture nl1 %}
{% endcapture %}{% capture existingSize %}{{input | size}}{% endcapture %}{% capture input %}{{ input | replace:nl2, nl1 }}{% endcapture %}{% capture newSize %}{{ input | size }}{% endcapture %}{% if existingSize == newSize %}{{ input }}{% else %}{% include trim %}{% endif %}

Hopefully this can be of help to others until Liquid solves this problem.