DEV Community

Matt Waler
Matt Waler

Posted on

Switch Statements Exist in Nunjucks!

TLDR: Clean up some conditional statements by using switch statements, not if-else blocks.

Despite being nowhere in the current documentation at the time of writing this, the switch statement, which can be very useful, is fully supported in Nunjucks. Here is an example below of how to use it.

<!-- Conditional -->
{% set test = false %}

<!-- Switch -->
{% switch test %}
  {% case true %}
    <p>This is true</p>
  {% default %}
    <p>This is false</p>
{% endswitch %}

<!-- Output -->
<p>This is false</p>
Enter fullscreen mode Exit fullscreen mode

Enjoy dryer conditional statements!

Discussion (2)

mathieuhuot profile image
Mathieu Huot

Wow, that's great! Thank you for sharing this. How did you learn that? It should be added to the documentation.

mattwaler profile image
Matt Waler Author

I randomly decided to try it and it worked!