DEV Community

loading...

Add a class in Nunjucks using a conditional statement

Giulia Chiola
Front-end Developer. 👾 Media engineer. ⚡ Facing life one bug at a time. 🔥 Easily bribed with chocolate. 🍫 she/her.
Originally published at giuliachiola.dev ・2 min read

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>
Enter fullscreen mode Exit fullscreen mode

HTML output

<p>true</p>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

HTML output

<div class="c-animals has-dog">...</div>
Enter fullscreen mode Exit fullscreen mode

Syntax n.2: implicit

Using double curly braces, Nunjucks evalued its content:

{% set arr = ['🐱', '🐶', '🐺'] %}

<p>{{ if '🐶' in arr }}</p>
Enter fullscreen mode Exit fullscreen mode

HTML output

<p>true</p>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

HTML output

<div class="c-animals has-dog">...</div>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 🤓

Discussion (0)

Forem Open with the Forem app