简体   繁体   中英

Nunjucks iterate over items in an array to display items in object

In javascript I can loop over an array to output my object as shown below.

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);
});

outputs

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)

outputs

number 2 - this is two

number 2 - this is two

I want to be able to do this in nunjucks as I want to control the order of display from myArr but also want the flexibility to be able to have a single page eg one.html where I can target one specifically eg {{testObj.one.title}} .

How can this be acheived with nunjucks? I have tried the below.

-- 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>

My ideal output to get to would be like the below where I can order my display based on myArr but for each item show the contents of their key in 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>

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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