node.js Jade - 模板引擎:如何检查变量是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5070841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:52:58  来源:igfitidea点击:

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

node.jspugexpress

提问by mbecker

I'm currently using Jade on a new project. I want to render a page and check if a certain variable is available.

我目前正在一个新项目中使用 Jade。我想呈现一个页面并检查某个变量是否可用。

app.js:

app.js

app.get('/register', function(req, res){
    res.render('register', {
        locals: {
          title: 'Register',
          text: 'Register as a user.',
        }
      });
});

register.jade:

register.jade

- if (username)
p= username
- else
p No Username!

I always get the following error:

我总是收到以下错误:

username is not defined

Any ideas on how I can fix this?

关于如何解决这个问题的任何想法?

回答by Chetan

This should work:

这应该有效:

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

回答by BMiner

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

如果您不介意测试虚假值而不是未定义的值,则比@Chetan 的方法更简单:

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

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

这是有效的,因为有点讽刺的名字locals是模板的根对象。

回答by avoid3d

if 'username' in this
    p=username

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

这是有效的,因为 res.locals 是模板中的根对象。

回答by Dominic Barnes

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.

如果你事先知道你想要一个特定的变量可用,但并不总是使用,我已经开始向 helpers 对象添加一个“默认”值。

app.helpers({ username: false });

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

这样,您仍然if (username) {可以避免灾难性故障。:)

回答by TK-421

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

'username' 不应该包含在 locals 对象中吗?

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

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

回答by Augustin Riedinger

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

创建了一个中间件,使该方法isDefined在我的视图中随处可用:

module.exports = (req, res, next) => {
  res.locals.isDefined = (variable) => {
    return typeof(variable) !== 'undefined'
  };  
  next();
};