0
在JavaScript中,我可以遍歷數組來輸出我的對象,如下所示。Nunjucks迭代數組中的項目以顯示對象中的項目
var myArr = ["one","two","three"]
var myObj = {
"one": {
"title": "ones",
"desc": "this is one"
},
"three": {
"title": "threes",
"desc": "this is three"
},
"two": {
"title": "twos",
"desc": "this is two"
}
}
myArr.forEach(function (value) {
console.log(myObj[value].title, myObj[value].desc);
});
輸出
ones this is one
twos this is two
threes this is three
console.log("number 2 - ",myObj[myArr[1]].desc)
console.log("number 2 - ",myObj["two"].desc)
輸出
number 2 - this is two
number 2 - this is two
我希望能夠做到這一點的nunjucks,我想控制從myArr
顯示的順序,但也希望能夠靈活地能夠有一個頁面如one.html哪裏我可以針對一個具體的例如{{testObj.one.title}}
。
這怎麼能與nunjucks達到?我已經嘗試了下面。
-- nunjucks --
<ul>
{% for item in testArr %}
<li>{{item}} - {{testObj.one.title}}</li>
{% endfor %}
</ul>
<ul>
{% for obj, item in testObj %}
<li>{{ obj }}: {{ item | dump }} - {{ item.title }} - {{ item.desc }}</li>
{% endfor %}
</ul>
--- output ---
<ul>
<li>one - ones</li>
<li>two - ones</li>
<li>three - ones</li>
</ul>
<ul>
<li>one: {"title":"ones","desc":"this is one"} - ones - this is one</li>
<li>three: {"title":"threes","desc":"this is three"} - threes - this is three</li>
<li>two: {"title":"twos","desc":"this is two"} - twos - this is two</li>
</ul>
我的理想輸出去會像下面的我在哪裏可以訂購基於myArr
我的顯示器,但每個項目顯示myObj
<ul>
<li>one - ones</li>
<li>two - twos</li>
<li>three - threes</li>
</ul>
感謝您的幫助!我以爲我已經嘗試過這樣的事情,這已經按預期工作了。 – ak85