Search code examples
nunjucks

Loop through object properties nunjucks


I've got following model:

items: {
    someId1: 
        {
            property1....
        },
    someId2: {...},
    someIdN: {...}
}

I would like to get a for-loop in my template (nunjucks) which goes through all the "someId's". Does anyone have any idea how? A normal for-loop does not work since it's not an array and since I use the "someId.." for a reference in another template I cannot put it to an array.

Any help would be awesome.


Solution

  • This answer is actually right on the Nunjucks homepage:

    <ul>
       {% for name, item in items %}
          <li>{{ name }}: {{ item }}</li>
       {% endfor %}
    </ul>
    

    In this case, name is the object property name, and item is the object property value, so you can also think of it like this:

    {% for key, value in object %}
    

    In your case this would be:

    <ul>
       {% for someId, item in items %}
          <li>{{ someId }}: {{ item.property1 }}</li>
       {% endfor %}
    </ul>
    

    As you can use the for loop for arrays and object/hashes.