Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get both the key and the index using Jade iteration

Tags:

As described here: http://jade-lang.com/reference/, it is easy enough to either get the index or the key. But is there a way to get both?

This:

ul   each val, index in {"day": "Wed", "link": "url", "message": "three"}     li#item-= index + ': ' + val 

Outputs this:

<ul>   <li id="item-">day: Wed</li>   <li id="item-">link: url</li>   <li id="item-">message: three</li> </ul> 

But I want this:

<ul>   <li id="item-0">day: Wed</li>   <li id="item-1">link: url</li>   <li id="item-2">message: three</li> </ul> 
like image 881
Scott Simpson Avatar asked Sep 27 '13 13:09

Scott Simpson


Video Answer


1 Answers

I think you only get an index if you are iterating over an array, so the jade documentation is a little confusing with its example. I'll give you three options for how to accomplish this. Choose your own adventure!

option 1: Keep your original input and build your own index

ul   -var index = 0   each val, key in {day: "Wed", link: "url", message: "three"}     li(id="item-#{index++}") #{key}: #{val} 

option 2: Change your input to an array of arrays

ul   each val, index in [["day", "Wed"], ["link", "url"], ["message", "three"]]     li(id="item-#{index}") #{val[0]}: #{val[1]} 

option 3: Change your input to an array of objects

ul   each val, index in [{day: "Wed"}, {link: "url"}, {message: "three"}]     li(id="item-#{index}") #{Object.keys(val)[0]}: #{val[Object.keys(val)[0]]} 

The first option is probably what you want, but the others may be interesting to read.

like image 160
David Weldon Avatar answered Sep 27 '22 18:09

David Weldon