Nunjucks 模板中的变量解构

Variable destructuring in Nunjucks template

当前变量在 for 循环中被称为属性:

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

希望跳过 for 中的 item. 部分:

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

类似于 ES6 解构:

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

是否可以在 Nunjucks 模板中将它们作为变量引用而不是 item 属性?

恕我直言,它的行为很危险。 FooBar 可以覆盖传递给模板和 {% set Foo = ... %} 变量。

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);