有没有一种方法可以通过使用Nunjucks过滤器从每个元素中提取特定属性来映射数组?
我想做以下事情,但我不知道如何使用内置的Nunjucks操作。
输入
{% set foods = [{name: "apple", colour: "green"},
{name: "plum", colour: "purple"},
{name: "cherry", colour: "red"}] %}
{{ foods | extractattr("colour") }}
输出
green,purple,red
const nunjucks = require('nunjucks');
const env = nunjucks.configure();
env.addFilter('map', function (arr, prop, ...etc) {
var f = typeof prop == 'function' ? prop : typeof this.env.filters[prop] == 'function' ? this.env.filters[prop] : (e) => e[prop];
return arr instanceof Array && arr.map(e => f(e, ...etc)) || arr;
});
const foods = [
{name: "apple", colour: "green"},
{name: "plum", colour: "purple"},
{name: "cherry", colour: "red"}
];
const html = env.renderString(`{{ foods | map('name') }}`, {foods});
console.log(html);