Highlighting liquid code in Jekyll
Recently I discovered that any liquid code we put in a Jekyll post gets evaluated by the liquid engine. This means that if you put in a code snippet for listing posts, you will see the actual HTML rendered, with all the posts.
As an example, try putting some liquid tags inside a markdown code block:
{{ "foo" | upcase }}
This is going to look like this:
FOO
So how are we seeing the raw liquid code above? There are two ways we can prevent liquid code from being evaluated.
The first option is to
wrap the code in the
{% raw %}
tag.
This would look like this:
{% raw %} {{ "foo" | upcase }} {% endraw %}
The second option is to use HTML entities
like {
and }
for the opening and closing curly braces, respectively.
We would need to type something like this
in the markdown file:
{{ "foo" | upcase }}
Unfortunately,
if we put this
inside markdown fenced code blocks
using ```
,
the actual entity will be rendered as-is
rather than the intended character.
We will need to explicitly wrap the code
with
<pre>
and
<code>
tags
to make this work.
Meta problem: How do we print the raw/endraw tags?
At this point,
you might be wondering:
If the raw/endraw tags
are used to escape the other tags,
how is the {% endraw %}
tag
appearing on this page?
Because if you tried wrapping
{% endraw %}
itself inside another set of raw/endraw tags,
it will look like this:
{% raw %}{% endraw %}{% endraw %}
The first endraw tag will terminate the block, and we will end up with a liquid error!
To solve this problem,
we will need to break up these tags
so that the opening tag token “{%
”
is a separate liquid variable.
You might want to put this line
before the code block,
or it will appear as an empty line.
{% assign open = "{%" %}
Now to render
the {% raw %}
tag,
we can do something like this:
{{ open }} raw %}
We can now go back to
printing the code
with raw and endraw tags.
To display the string
“{% raw %}{% endraw %}{% endraw %}
”,
we need to write:
{{ open }} raw %}{{ open }} endraw %}{{ open }} endraw %}
In case you are wondering, what kind of liquid code did it take to print the code block above, here you are:
{% raw %}{{ open }} raw %}{{ open }} endraw %}{{ open }} endraw %}{% endraw %}
Now, we really have to stop. If you’re curious what it took to print this line, you can always look up the markdown code for this post.
Here are a couple of other articles that helped me figure out how to escape liquid tags in Jekyll. (Bonus: you can look at their markdown source to see it in action.)
- Writing the endraw tag in Jekyll code blocks (markdown)
- Liquid ‘raw’ Tag and Fenced Code Blocks (markdown)
PS. I couldn’t help it. Here’s the liquid code for that last code block. This time, I really am done! ;)
{{ open }} raw %}{% raw %}{{ open }} raw %}{{ open }} endraw %}{{ open }} endraw %}{% endraw %}{{ open }} endraw %}