Jade template engine - Each Iteration Offset

Go To StackoverFlow.com

10

Is there a way to offset the 'each' iteration when using the Jade template engine?

for example, when passing in the object named list:

ul
   each item in list
      li #{item}

Will output

<ul>
   <li> Item 1 </li>
   <li> item 2 </li>
   <li> item 3.....
...
</ul>

But I want the first item to be displayed differently than the rest of the items, like so:

<ul>
   <li> Item 1: First Item in list! </li>
   <li> item 2 </li>
   <li> item 3.....
...
</ul>

So does anyone know a way to offset the 'each' statement in Jade so that I can render the first item separately and then render each following item starting at the 2nd index?

2012-04-04 02:07
by Steve Mason


21

each item, i in list
  li= item
  if i === 1
    | : First item in list!
2012-04-04 09:02
by Jonathan Ong
Thanks! I ended up using if - else to display the first item differently (i'm using partials, not the exact example i gave). Also, I had to make i === 0 to get the first item. Thanks alot - Steve Mason 2012-04-04 14:27
Oops forgot about that lo - Jonathan Ong 2012-04-04 18:04
Doesn't work currently with Jade4J :- - Jackie 2014-04-14 14:50
@Jackie See my answer for current solution and examples - Levi 2014-11-09 17:44


2

If @Johnathan's answer does not work for you: In Jade 1.7 the following works:

for item, i in list
    li= item
    if i === 0
        | : First item in list!

http://www.learnjade.com/tour/iteration/

Also note the 0 index vs 1 index.

2014-11-09 17:43
by Levi
Ads