Eddie Brunstedt Eddie Brunstedt - 5 months ago 27
Node.js Question

How do I iterate a table in Jade assigning each <td> with a unique id?

I am trying to create a table containing 9 rows with 9 columns. I want to create this by iterating through it with the help of Jade. I'm quite new to Jade so I am probably way off here, but this is my code now;

var test1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8']
var test2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8']
for (var i = 0; i < test1.length; i++) {
tr
for (var o = 0; i < test2.length; o++) {
td(id='square-'+test1[i]+test2[o])
}
}


This (obviously?) gives me a syntax error.

How do I go about to iterate a table with 9 rows and 9 cols and give them id=square00, square01, square02 etc..?

Answer

Something like this should do the trick:

- var rows = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
- var columns = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];

table
    tbody
        each row in rows
            tr
                each column in columns
                    td(id="square-" + row + "-" + column) #{row} - #{column}

Note that the javascript is prefaced by - , with the exception of the lines that are doing the iterating. That's because each is a reserved keyword that Jade (now Pug) recognizes as meaning you want to iterate.

Good luck!