0

Say I have a set of variables name1, name2, name3... etc, which I'm writing out in a div. Right now I can print it out using #{name1} #{name2} #{name3} etc but is it possible to do this with a for loop in Jade

- for(var i = 0; i<3; i++) { div #{"name" + i} }

So i want the output to be:

div #{name1}
div #{name2}
div #{name3}

Something like this in order to print out the first 3 elements.... hope i made some sense. When I do it the way I have above Jade seems to think I'm just putting a string into the div instead of the variable. If it matters I'm using Express.JS for my application. ty

Vinicius Braz Pinto
  • 8,209
  • 3
  • 42
  • 60
Roman
  • 155
  • 1
  • 2
  • 8

1 Answers1

0

Jade seems to think I'm just putting a string into the div

Because you are!

When you say "...instead of the variable" what you really mean is a reference to its value. This is what for loops excel at. But "name" + i creates a string and variables are not referenced as strings - with one important exception: object properties.

You have two choices:

var names = [name1, name2, name3];
for (var i = 0; i < 3; i = i + 1) {
    div #{names[i]}
}

or...

var names = {
    name1: name1,
    name2: name2,
    name3: name3
};
for (var k in names) {
    if (Object.prototype.hasOwnProperty.call(names, k)) {
        div #{names[k]}
    }
}
Seth Holladay
  • 8,951
  • 3
  • 34
  • 43