Search code examples
javascriptnunjuckseleventy

Is there a way to extract an attribute using a Nunjucks filter?


Is there a way of mapping an array by extracting a specific attribute from each element using a Nunjucks filter?

I'd like to do something like the following, but I can't figure out how to do it using the inbuilt Nunjucks operations.

Input

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

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

Output

green,purple,red

Solution

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