Search code examples
templatingnunjucks

Nunjucks nested object array field printing


My array data:

data = [
  { field: { name:"name1", title:"title1" } },
  { field: { name:"name2", title:"title2" } },
  { field: { name:"name3", title:"title3" } }
];

I want to write name fields like this:

Expected Output

name1.name2.name3


I need join these object's specified field values but I don't know how to get them like this.

What I tried and failed =>

data | selectattr("field") | selectattr("name") | join(".") }}


Solution

  • selectattr-filter only filter data elements. Therefore, when you apply selectattr('name'), nunjucks try to filter data by elements having name-field (none of them) and returns the empty result.

    The simplest way to achive name1.name2.name3 is to use a custom filter

    const nunjucks  = require('nunjucks');
    const env = nunjucks.configure();
    
    env.addFilter('map', function (arr, prop, ...etc) {
        const f = typeof prop == 'function' ? 
            prop : typeof env.filters[prop] == 'function' ? 
            env.filters[prop] : (e) => e[prop]; 
    
        return arr instanceof Array && arr.map(e => f(e, ...etc)) || arr;
    });
    
    const data = [
      {field: {name: "name1", title: "title1"}},
      {field: {name: "name2", title: "title2"}},
      {field: {name: "name3", title: "title3"}}
    ];
    
    const html = env.renderString(`{{ data | map('field') | map('name') | join('.') }}`, {data});
    
    console.log(html);