How to limit number of iterations when looping through object in nunjucks

Issue

I have a js object like this:

var data = [
    { src: "src1", name: "name 1" }, 
    { src: "src2", name: "name 2" }, 
    { src: "src3", name: "name 3" }
]

I am looping through it with Nunjucks:

{% for object in data %}
    {{object.src}}
{% endfor %}

But I want to limit the number of iterations to 2.

How do I do that with Nunjucks?

I know there is a range option but I couldn’t find how to use it in this case.

Solution

You could accomplish this a couple different ways:

A) Use loop.index0 special variable (Demo in Codepen)

Inside a for loop, you can use loop.index0 instead limit-var

{% for obj in data %}
    {% if loop.index0 < 2 %}    
        {{obj.src}}: {{obj.name}}
    {% endif %}
{% endfor %}

B) Add Custom Filter (Demo in Codepen)

But more readable is add custom filter limit and use it

var nunjucks  = require('nunjucks');
var env = nunjucks.configure();

var data = [
    {src: "src1", name: "name 1"}, 
    {src: "src2", name: "name 2"}, 
    {src: "src3", name: "name 3"}
];

env.addFilter('limit', function(arr, limit) {
    return arr.slice(0, limit);
});

var res = nunjucks.renderString(`
    {% for obj in data | limit(2) %}
    {{obj.src}}: {{obj.name}}
    {% endfor %}`, 
    {data}
);

console.log(res);

C) Use native slice() function (Demo in Codepen)

{% for obj in data.slice(0, 2) %}
    {{obj.src}}: {{obj.name}}
{% endfor %}

Answered By – Aikon Mogwai

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.