Search code examples
javascriptarraysfor-loopnunjucks

Nunjucks: Select specific items from array in for loop


I need to select specific items from a large array, say [5, 21, 83, 74, 12], and my list looks like this:

{
  "list:" [
    { "title": "Blue" },
    { "title": "Green" },
    { "title": "Yellow" } ...
  ]
}

I was thinking about a for loop, but am not sure of the syntax or filters I should use. How should I modify this code to accomplish the above?

{% for item in list %}
    {% item %}
{% endfor %}

Solution

  • You can add a custom filter if you need to apply filter more than once.

    var nunjucks  = require('nunjucks');
    var env = nunjucks.configure();
    env.addFilter('myfilter', arr => arr.filter(e => e.title == 'Green'));
    
    var html = env.renderString(`
        {% for item in list | myfilter %} 
            {{item.id}} {{ item.title}} 
        {% endfor %}
        `, 
        { 
            list: [
                { id: 1, title: 'Blue' },
                { id: 2, title: 'Green' },
                { id: 3, title: 'Yellow' },
                { id: 4, title: 'Green' }
            ]
        }
    );
    
    console.log(html);
    

    Another way is to use if each time

    {% for item in list %}
        {{ item if item.title == 'Green' }}
    {% endfor %}
    

    or

    {% for item in list %}
        {% if item.title == 'Green' %}
            {{ item }}
        {% endif %} 
    {% endfor %}