Liquid is the templating engine that powers Jekyll. While rendering variables like {{ page.title }} is straightforward, Liquid holds a lot of power under the hood.
In this guide, we will explore some advanced techniques to keep your Jekyll code DRY and organized.
1. Advanced Looping Parameters
When using the for tag, you are not limited to just iterating over collections. You can slice, limit, and offset your loops.
<!-- Skip the first 2 posts and show the next 5 -->
{% for post in site.posts offset:2 limit:5 %}
<h3>{{ post.title }}</h3>
{% endfor %}
2. Using Custom Variable Assignments
Assigning variables (assign or capture) allows you to build complex logic securely within a single template.
{% assign hero_class = "default-hero" %}
{% if page.featured %}
{% assign hero_class = "featured-hero" %}
{% endif %}
<div class="{{ hero_class }}">
<!-- Content here -->
</div>
You can also use capture to store entire blocks of HTML into a variable:
{% capture alert_box %}
<div class="alert">
<strong>Warning:</strong> {{ page.warning_text }}
</div>
{% endcapture %}
{{ alert_box }}
3. Map, Where, and Sort Filters
These filters transform arrays and are crucial when trying to list specific items from a large collection or data file.
where: Filters an array where a property equals a specific value.sort: Sorts an array based on a property.
<!-- Find all tutorials and sort them by date -->
{% assign tutorials = site.posts | where: "categories", "Tutorials" | sort: "date" %}
{% for tut in tutorials %}
<a href="{{ tut.url }}">{{ tut.title }}</a>
{% endfor %}
(Remember that Jekyll Builder handles all this complex logic through visual components, letting you keep your codebase scalable without touching Liquid directly!)