Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript code in Jade views - if(variable) shows undefined instead of passing

So this is a recurring issue I have and haven't found another example on SO so here goes:

When rendering Jade templates I get 'variableName' undefined even when using -if(variableName) in the template.

Example (I'm using this as a partial for 'info' flash messages):

-if(info)
  - if(info.length){
   ul
   -info.forEach(function(info){
     li= info
  -})
-}

This returns 'info' is not defined instead of not rendering anything when there isn't a flash/info message. Does anyone know what I'm doing wrong?

I'm aware of the typeof(variable) != 'undefined option as mentioned. If I wanted to do something like -if (typeof(req.session.user) != 'undefined') I would have to do 3 nested `if (typeof(req) != 'undefined'. Is this my only option?

like image 607
JohnAllen Avatar asked Apr 21 '11 18:04

JohnAllen


1 Answers

try if(typeof info !== "undefined").

I'm not too sure but I think they use with to inject variables into the scope of your view.

with({}) {
    if (foo) {
         console.log("foo"); // fails foo is not defined.
    }
}

with({}) {
    if (typeof foo !== "undefined") {
         console.log("foo"); // no error
    }
}
like image 170
Raynos Avatar answered Sep 22 '22 12:09

Raynos