【问题标题】:Is there a way to extract an attribute using a Nunjucks filter?有没有办法使用 Nunjucks 过滤器提取属性?
【发布时间】:2021-08-02 14:12:16
【问题描述】:

有没有办法通过使用 Nunjucks 过滤器从每个元素中提取特定属性来映射数组?

我想做以下类似的事情,但我不知道如何使用内置的 Nunjucks 操作。

输入

{% set foods = [{name: "apple", colour: "green"}, 
                {name: "plum", colour: "purple"}, 
                {name: "cherry", colour: "red"}] %}

{{ foods | extractattr("colour") }}

输出

green,purple,red

【问题讨论】:

  • 看看this问题。

标签: javascript nunjucks eleventy


【解决方案1】:
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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2013-04-13
    相关资源
    最近更新 更多