node.jstemplatesnpmtemplate-enginenunjucks

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:


Solution

  • 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.