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


Question

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

app.js:

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

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?

1
78
1/31/2018 4:29:46 PM

Accepted Answer

This should work:

- if (typeof(username) !== 'undefined'){
  //-do something
-}
105
12/10/2012 1:25:51 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon