Digiguru.co.uk

How to output mustache templates in a jekyll site

31 Mar 2015

Reading time: 1 minute

I was having difficulty rendering a mustache template out as a code sample.

Here was my code sample…

{{#.}}

<p>Hello, my name is {{name}}.</p>
<p>I am from {{hometown}}.</p>
<p>I have {{kids.length}} kids:</p>
<ul>
{{#kids}}
    <li>{{name}} is {{age}}</li>
{{/kids}}
</ul>
{{#.}}

So you write the above in a markdown file, and try wrapping it in {% highlight html %}

{% highlight html %} 
...
{% endhighlight %}

And the output looks on the page as follows…

<p>Hello, my name is .</p>
<p>I am from .</p>
<p>I have  kids:</p>
<ul>

    <li> is </li>

</ul>

Hmm - not right. Perhaps I need a different highlighter - mustache?

{% highlight mustache %} 
...
{% endhighlight %}

But there was no change.

After a bit of research I discovered the raw blocks, so wrapping the code in raw it output like this…

{{#.}}

Hello, my name is {{name}}.

I am from {{hometown}}.

I have {{kids.length}} kids:

    {{#kids}}
  • {{name}} is {{age}}
  • {{/kids}}

{{#.}}

Almost - but there’s no code tag wrapped around it. How about if we just add the code tag around it in the markdown file…

{{#.}}

Hello, my name is {{name}}.

I am from {{hometown}}.

I have {{kids.length}} kids:

    {{#kids}}
  • {{name}} is {{age}}
  • {{/kids}}

{{#.}} </code>

No - the code black only works on the first line before it’s auto closed by the browser.

I tried various methods of outputting it until I finally realised I need to wrap the original code script with.

{% highlight html %}
{% raw %}
...
{% endraw %}
{% endhighlight %}

And this works!

{{#.}}

<p>Hello, my name is {{name}}.</p>
<p>I am from {{hometown}}.</p>
<p>I have {{kids.length}} kids:</p>
<ul>
{{#kids}}
    <li>{{name}} is {{age}}</li>
{{/kids}}
</ul>
{{#.}}

Excellent!

But… you think that’s crazy? - it gets even weirder when you see what I had to write to make jekyll output the wrapper script I described above…

{{ "{% highlight html "}}%}
{{ "{% raw "}}%}
...
{{ "{% endraw "}}%}
{{ "{% endhighlight "}}%}

Basically I am using escaped code to output the “raw” tag. If I don’t do that then liquid templates attempt to compile the interior as raw text, and get’s a bit confused by opening and closing tags.