Sara Sara - 1 year ago 103
Jade Question

How to call an array's value with a variable within jade

Can't figure out why exactly a variable can't be used to help call a value in an array with JS/Jade. This is being called inside a script on a


The array contains roughly 400 entries and one of the entries is as follows:

myFood[10]['Cake'] = 50

When using the variable
instead of directly putting in the number
an error occurs.


alert (i) // 10
alert (#{myFood[10]['Cake']}) // 50


alert (#{myFood[i]['Cake']}) // Error, Cannot read property 'Cake' of undefined.

Answer Source

First of all, know that Jade recently was renamed to "pugjs".

I'm assuming that i is a javascript variable as you stated in the comments.

The pug (jade) context and the browser Javascript context are two very different things, so if you define i in browser Javascript, jade will not see it as a variable, just plaintext waiting to be interpreted by the browser. That's why myFood[i] is undefined and thus resulting in this error.

The correct way to define a jade variable is by prefixing your line by a dash (-), as described here.

The full code is:

- var i = 10;
alert (#{i})                  // 10
alert (#{myFood[10]['Cake']}) // 50

You note that I also changed the first alert to tell pug to replace the #{i} part by the actual value of i.

If you want to access each value I would highly suggest that you use loops instead of using an i to access the array.

Mixing pug and javascript is a bit tricky, so good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download