Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nunjucks: 'if' with multiple 'and' or 'or' condition

Today my team mate was struggling on how to add multiple conditions with 'and' or 'or' in an if statement in Nunjucks template. After a lot of search he found the answer but not on Stackoverflow. I am not sure if the answer is already posted somewhere in SO but thought to post it now to narrow down future searches.

Below is the answer:

like image 760
akhileshnair Avatar asked Mar 08 '17 17:03

akhileshnair


People also ask

How do you define a variable in Nunjucks?

var njglobals = require('nunjucks/src/globals'); njglobals. someVar = 'someValue'; You can now use someVar in your templates. Be sure not to overwrite any of the existing properties of the njglobals object, though (for [email protected] , they are range , cycler and joiner ).

What is Nunjucks used for?

A rich, high-performance JavaScript templating language, supported by all modern browsers. Nunjucks is customizable with extensions and filters; it offers inheritance, asynchronous control, autoescaping and other features. It also supports any version of Node.

How do I comment in Njk?

Comments. You can write comments using {# and #} . Comments are completely stripped out when rendering.


1 Answers

Answer:

As we know Nunjucks is inspired by Jinja2 python's template engine, the if statement is similar to it.

// And Snippet {% if (VARIABLE > 10) and (VARIABLE < 20) %}     //  {% endif %}  // Or Snippet {% if (VARIABLE == 10) or (VARIABLE == 20) %}     // {% endif %} 

Thats it !!!

Couldn't find this on Nunjucks documentation either. I believe this answer will be helpful as coders working on Nunjucks tend to search with keyword Nunjucks and not with Jinja.

like image 77
akhileshnair Avatar answered Oct 10 '22 23:10

akhileshnair