In Nunjucks we can use a conditional statement in two ways:
-
explicit using the
{% if %}
keyword, - or implicit using the
{{ }}
expression.
Note: I did not find any reference about these names β implicit/explicit β in the Nunjucks official documentation π, I just named to easily distinguish the two syntax in this tutorial π.
Syntax n.1: explicit
Using an explicit {% if %}
keyword, Nunjucks checks if the condition is met
{% set arr = ['π±', 'πΆ', 'πΊ'] %}
<p>{% if 'πΆ' in arr %}{% endif %}</p>
HTML output
<p>true</p>
Using this method, we can add an HTML class when a specific condition is met
{% set arr = ['π±', 'πΆ', 'πΊ'] %}
<div class="c-animals {% if 'πΆ' in arr %}has-dog{% endif %}">...</div>
HTML output
<div class="c-animals has-dog">...</div>
Syntax n.2: implicit
Using double curly braces, Nunjucks evalued its content:
{% set arr = ['π±', 'πΆ', 'πΊ'] %}
<p>{{ if 'πΆ' in arr }}</p>
HTML output
<p>true</p>
Using this method, we can add an HTML class when a specific condition is met
{% set arr = ['π±', 'πΆ', 'πΊ'] %}
<div class="c-animals {{ 'has-dog' if 'πΆ' in arr }}">...</div>
HTML output
<div class="c-animals has-dog">...</div>
Note that the HTML output is exactly the same! π
To sum up
{% set arr = ['π±', 'πΆ', 'πΊ'] %}
{# 1. explicit #}
<div class="c-animals {% if 'πΆ' in arr %}has-dog{% endif %}">...</div>
{# 2. implicit #}
<div class="c-animals {{ 'has-dog' if 'πΆ' in arr }}">...</div>
Personally, I use both syntaxes in my Nunjucks files, and to choose which one to use I go with this logic:
- if there is just one condition to met and it is quite simple, I use the implicit syntax
- else I use the explicit one π€
Top comments (0)