Add a class in Nunjucks using a conditional statement

In Nunjucks we can use a conditional statement in two ways:

  1. explicit using the {% if %} keyword,
  2. 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 🤓