Skip to content

Liquid Tag Parameters

Posted on:October 14, 2015

This is a nifty one.

I wanted to create manual categories for my coding posts, so I ended up doing something like this in my coding/index.html (a simplified excerpt):

<div>
  <h3>Ruby</h3>
  <ul>
    {% raw %}{% for post in site.posts %} {% if post.categories contains "ruby"
    %} {{ post.title }} {% endif %} {% endfor %}
  </ul>
 
  <h3>Javascript</h3>
  <ul>
    {% for post in site.posts %} {% if post.categories contains "javascript" %}
    {{ post.title }} {% endif %} {% endfor %}
  </ul>
 
  <h3>Erlang</h3>
  <ul>
    {% for post in site.posts %} {% if post.categories contains "erlang" %} {{
    post.title }} {% endif %} {% endfor %}
  </ul>
 
  <!-- and so on -->
</div>

… which was really ripe for DRYing up. The problem was that the partial would need to accept a parameter of some sort (for the category name). The official Liquid documentation leaves much to be desired, but there’s a tiny part in the Templates section of the Jekyll documentation that saved the day:

You can also pass parameters to an include. Omit the quotation marks to send a variable’s value. Liquid curly brackets should not be used here:

{% include footer.html param="value" variable-param=page.variable %}

These parameters are available via Liquid in the include:

{{ include.param }}

So I abstracted the above into a partial, naturally so:

<!-- _includes/post-category.html -->
<h3>{{ include.name | capitalize }}</h3>
<ul>
  {% for post in site.posts %} {% if post.categories contains include.name %} {{
  post.title }} {% endif %} {% endfor %}
</ul>

and the resulting index.html:

<div>
  {% include post-category.html name="ruby" %} {% include post-category.html
  name="javascript" %} {% include post-category.html name="erlang" %}{% endraw
  %}
</div>

Neato!