Rob Rob - 4 months ago 13
Node.js Question

How to insert new tr every third iteration in Jade

I'm new in node.js and Jade.

I searched for solutions without success (maybe I asked wrong questions in google, I don't know).

I want to create table rows in

each
loop in Jade. The thing is that after every 3rd
td
I want insert new
tr
. Normally it's quite simple but with Jade I simply can't achieve that.

My Jade file:



table
thead
tr
td Header
tbody
each item, i in items
if (i % 3 === 0)
tr
td
a(href="#{baseUrl}/admin.html?id=#{item.id}")


I know that something is wrong with my
if
statement. I tried many configurations without luck. I'm sure that it will be quite easy issue.

Thanks in advance for help!

EDIT



Based on @Laurent Perrin answer I modified a little my code. Now it creates
tr
, then 3
td
and then new
tr
so it's a little closer...

New Jade



if (i % 3 === 0)
tr
td: a(href="#{baseUrl}/admin.html?id=#{item.id}") dsdsd #{i}


Generated HTML



<tr></tr>
<td><a href="...">0</a></td>
<td><a href="...">1</a></td>
<td><a href="...">2</a></td>
<tr></tr>

Answer

EDIT: this code should do what you want, but it's not very elegant:

table
   thead
     tr: td Header
      tbody
        - for(var i = 0, nbRows = items.length/3; i < nbRows; i++) {
        tr
           if items[3*i]
             td: a(href="#{baseUrl}/admin.html?id=#{items[3*i].id}")
           if items[3*i + 1]
             td: a(href="#{baseUrl}/admin.html?id=#{items[3*i + 1].id}")
           if items[3*i + 2]
             td: a(href="#{baseUrl}/admin.html?id=#{items[3*i + 2].id}")
       - }

What you could do instead is tweak your model to make it more Jade-friendly, by grouping items by rows:

function getRows(items) {
    return items.reduce(function (prev, item, i) {
        if(i % 3 === 0)
            prev.push([item]);
        else
            prev[prev.length - 1].push(item);

        return prev;
    }, []);
}

This will turn:

[{id:1},{id:2},{id:3},{id:4},{id:5}]

into:

[
    [{id:1},{id:2},{id:3}],
    [{id:4},{id:5}]
]

Then your jade code becomes much simpler:

table
     thead
         tr: td Header
     tbody
        each row in rows
            tr
                each item in row
                    td: a(href="#{baseUrl}/admin.html?id=#{item.id}")