Loop through object properties nunjucks

主宰稳场 提交于 2019-12-09 15:08:39

问题


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.


回答1:


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.




回答2:


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: {...}
}


来源:https://stackoverflow.com/questions/20990516/loop-through-object-properties-nunjucks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!