nunjucks

Nunjucks Set a Variable with a {% set %} {% endset %} an inline if else


I'm having some issues with a nunjucks code that a peer says has a valid syntax:

{% set variable%} {{ a if a > 0 else 1 }} {% endset %}

I know that they included inline if else but I can't find an example that combines it with a set. Thanks in advance, hope you have a happy day


Solution

  • Your code is correct

    {% set myvar %} 
       {{ a if a > 0 else 1 }} 
    {% endset %}
    {{ myvar }}
    

    For Node.js

    const nunjucks  = require('nunjucks')
    const env = nunjucks.configure()
    
    const html = env.renderString(`
    {% set myvar %} 
       {{ a if a > 0 else 1 }} 
    {% endset %}
    {{ myvar }}`, 
    { a: -10 });
    
    console.log(html)