DEV Community

Giulia Chiola
Giulia Chiola

Posted on • Originally published at giuliachiola.dev

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>
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 πŸ€“

Top comments (0)