[英]Variable destructuring in Nunjucks template
当前变量被称为for
循环内for
属性:
{% id, item in items %}
<div>
{{ id }}
{{ item.foo }}
{{ item.bar }}
{{ item.baz }}
...
希望跳过item.
部分for
:
...
<div>
{{ id }}
{{ foo }}
{{ bar }}
{{ baz }}
与ES6解构类似:
for (const [id, {foo, bar, baz}] of Object.entries(items)) ...
是否可以在Nunjucks模板中将它们引用为变量而不是item
属性?
恕我直言,这是危险的行为。 Foo
和Bar
可以覆盖传递给模板和{% 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.