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