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

So this is a recurring problem that I have and have not found another example for SO, like this:

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

Example (I use this as partial for flash info messages):

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

This returns “information” rather than “nothing” if there is no flash information. Does anyone know what I'm doing wrong?

I know 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'. This is my only option ?

+6
source share
4 answers

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

I'm not too sure, but I think they use with to input variables into your view area.

 with({}) { if (foo) { console.log("foo"); // fails foo is not defined. } } with({}) { if (typeof foo !== "undefined") { console.log("foo"); // no error } } 
+10
source

Yes, most template modules complete the entire compiled template function in instruction c. Otherwise, variables can be taken into account when analyzing the template, but I think that almost all template mechanisms use with ().

One solution would be to always make sure that the “information” is always in the local object when rendering this template. You can do this by explicitly specifying the information as undefined or any other false value.

 var locals = { info: undefined, ... }; 
+1
source

just specify the IF variable of the variable variable undefined:

 input(name="company[name]" type="text",placeholder="Name",value="#{company.name || ''}") 
0
source

instead:

 var params = { "info": [ "a value" ] }; -if(info) - if(info.length){ ul -info.forEach(function(info){ li= info -}) -} 

using:

 var params = { "namespace": { "info": [ "a value" ] } }; -if(namespace.info) - if(namespace.info.length){ ul -namespace.info.forEach(function(info){ li= info -}) -} 

Since a "namespace" will always exist, and you can reference Object.key without the error "undefined", this will work better for you.

-Jeff

-1
source

Source: https://habr.com/ru/post/886412/


All Articles