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

拥有回忆 提交于 2019-12-10 04:33:58

问题


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?


回答1:


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
    }
}



回答2:


Yes, most templating engines wrap the entire compiled template function in a with statement. It is possible to do otherwise by taking the variables into account when parsing the template, but I think nearly all templating engines use with().

One solution would be to always make sure "info" is always in the locals object when rendering that template. You could do this by explicitly setting info to undefined or any other falsey value.

var locals = { info: undefined, ... };



回答3:


simply specify the variable value IF variable undefined:

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



回答4:


instead of:

var params = {
    "info": [
        "a value"
    ]
};

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

use:

var params = {
    "namespace": {
        "info": [
            "a value"
        ]
    }
};


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

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

-jeff



来源:https://stackoverflow.com/questions/5748087/using-javascript-code-in-jade-views-ifvariable-shows-undefined-instead-of-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!