繁体   English   中英

Nunjucks遍历数组中的项目以显示对象中的项目

[英]Nunjucks iterate over items in an array to display items in object

在javascript中,我可以遍历数组以输出我的对象,如下所示。

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 --
<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>
<ul>
  {% for item in myArr %}
    <li>{{item}} - {{myObj[item].title}}</li>
  {% endfor %}
</ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM