Writing Liquid Template in Markdown Code Blocks with Jekyll

Apr 26, 2016    

When I was writing another blog post on listing blog posts by tags in Jekyll, I came across a curious problem when I try to write liquid template code in my markdown file. Evidently, when Jekyll compiles the static web files, it tries to process all the double curly brackets like {{ and {%, which of course leads to errors.

Apparently this is not a bug, but just a caveat of using a templating language with markdown. Well there are a few workarounds, here’s what I ended up doing.

inception Inception of raw liquid templating in liquid templating with markdown

Workaround 1: Using Liquid’s Raw Tag

One option is to use Liquid’s {% raw %} tag. Raw temporarily disables tag processing until the {% endraw %}. The markdown code would then be something like this:

method1 You won’t believe how confused Jekyll was when I try to write 2 {% raw %} one after another in a markdown codeblock. So I resorted to just taking a screenshot…

to render this beautifully:

<ul>
{% for tag in site.tags %}
  {% assign name = tag | first %}
  {% assign posts = tag | last %}
  <li>{{ name | camelize | replace: "-", " " }} has {{posts | size}} posts</li>
{% endfor %}
</ul>

Workaround 2: Using Jekyll Variables for Left Curly Braces

A second workaround is to use Jekyll’s site or page variables to output the left curly braces {. I found this idea from Nate Eagle’s blog post and it breaks up the left side of Liquid tags {% and outputs {{ so that Jekyll does not process it.

In the YAML frontmatter of the post, you can create a variable lcb with the left curly brace as a string, like so:

---
layout: "post"
title: "Writing Liquid Template in Markdown Code Blocks with Jekyll"
date: "2016-04-26 21:00"
tags: [jekyll, website, liquid]
lcb: "{"
---

Then in the markdown blockcode, you can use {{ page.lcb }}

2

which renders in HTML nicely like this:

<ul>
{% for tag in site.tags %}
  {% assign name = tag | first %}
  {% assign posts = tag | last %}
  <li>{{ name | camelize | replace: "-", " " }}
      has {{posts | size}} posts</li>
{% endfor %}
</ul>

Once the left curly braces are separated, the rest of the line won’t be processed as Liquid template anymore.

You could also create a site variable by adding the lcb: "{" in your _config.yml. Then just reference {{site.lcb}} instead.

I know there are a few other workarounds to escape the left curly braces, but these are the 2 methods I found the most useful to me. If you came across a better solution though, pelase let me know!

-->