Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through object properties nunjucks

Tags:

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.

like image 334
Tikkes Avatar asked Jan 08 '14 08:01

Tikkes


2 Answers

This answer is actually right on the Nunjucks homepage:

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

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.

like image 99
Jasper Moelker Avatar answered Oct 20 '22 22:10

Jasper Moelker


You can use nested loops like this:

<ul>
  {% for item in items %}
    {% for something in item.someId1 %}
      <li>
        {{ something.property1 }}
      </li>
    {% endfor %}
  {% endfor %}
</ul>

For this json object:

items: {
  someId1: {
    property1: "It makes you want to shout! Raise your hands up and..."
  },
  someId2: {...},
  someIdN: {...}
}
like image 35
Juan Figueroa Avatar answered Oct 20 '22 23:10

Juan Figueroa