Nunjucks
22 Jun, 2023
👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page
- Built-in filters: https://mozilla.github.io/nunjucks/templating.html#builtin-filters
Tags Jump to heading
If Jump to heading
{% if variable %}
It is true
{% endif %}
For Jump to heading
<ul>
{% for item in items %}
<li>{{ item.title }}</li>
{% else %}
<li>This would display if the 'item' collection were empty</li>
{% endfor %}
</ul>
Another example that makes use of loop.index
and loop.length
:
{% for value in array %}
<li>[{{ loop.index }} of {{ loop.length }}] {{ value }}
<pre>{{ loop | inspect }}</pre>
{% if not loop.last %}
<hr/>
{% endif %}
</li>
{% endfor %}
Debugging Jump to heading
There are two useful ways to debug data in Nunjucks templates.
dump
filter
Jump to heading
Prints the data to the page
{{ data | dump }}
log
filter
Jump to heading
Logs the data to your terminal
{{ data | log }}
They can be used together:
{{ data | dump | log }}
Active class on links Jump to heading
<a
class="{{ 'active' if '/' === page.url }}"
href="{{ '/' | url }}"
>
Home
</a>
<!-- or to set an active link for all items in a subdirectory -->
{{ 'active' if '/blog' in page.url }}
More examples: https://bryanlrobinson.com/blog/using-nunjucks-if-expressions-to-create-an-active-navigation-state-in-11ty/
← Back home