Jade - Template Engine: How to check if a variable exists

强颜欢笑 提交于 2019-11-28 15:37:56
Chetan

This should work:

- if (typeof(username) !== 'undefined'){
  //-do something
-}
BMiner

Simpler than @Chetan's method if you don't mind testing for falsy values instead of undefined values:

if locals.username
  p= username
else
  p No Username!

This works because the somewhat ironically named locals is the root object for the template.

if 'username' in this
    p=username

This works because res.locals is the root object in the template.

If you know in advance you want a particular variable available, but not always used, I've started adding a "default" value to the helpers object.

app.helpers({ username: false });

This way, you can still do if (username) { without a catastrophic failure. :)

Shouldn't 'username' be included in the locals object?

https://github.com/visionmedia/jade/tree/master/examples

Created a middleware to have the method isDefined available everywhere in my views:

module.exports = (req, res, next) => {
  res.locals.isDefined = (variable) => {
    return typeof(variable) !== 'undefined'
  };  
  next();
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!