Search code examples
javascriptecmascript-6nunjucks

Variable destructuring in Nunjucks template


Currently variables are referred as properties inside for loop:

{% id, item in items %}
  <div>
    {{ id }}
    {{ item.foo }}
    {{ item.bar }}
    {{ item.baz }}
    ...

It is desirable to skip item. part in for:

  ...
  <div>
    {{ id }}
    {{ foo }}
    {{ bar }}
    {{ baz }}

Similarly to ES6 destructuring:

for (const [id, {foo, bar, baz}] of Object.entries(items)) ...

Is it possible to refer them as variables and not item properties in Nunjucks template?


Solution

  • Imho, it's behavior is danger. Foo and Bar can override passed to template and {% set Foo = ... %} vars.

    var nunjucks  = require('nunjucks');
    var env = nunjucks.configure();
    
    env.addGlobal('destruct', function(obj) { 
        for (var key in obj)
            this.ctx[key] = obj[key];
    })
    
    var res = nunjucks.renderString(`
        {% for id, item in items %}
            {{destruct(item)}}
            {{id}} - {{foo}} - {{bar}}
        {% endfor %}
        `,
        {
            items: {
                A: {id: 10, foo: 'fooA', bar: 'barA'}, 
                B: {id: 20, foo: 'fooB', bar: 'barB'}
            }
        }
    );
    
    console.log(res);