83

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?

gandreadis
  • 3,004
  • 2
  • 26
  • 38
mbecker
  • 1,663
  • 3
  • 19
  • 24

7 Answers7

108

This should work:

- if (typeof(username) !== 'undefined'){
  //-do something
-}
Logan
  • 10,649
  • 13
  • 41
  • 54
Chetan
  • 46,743
  • 31
  • 106
  • 145
94

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.

broofa
  • 37,461
  • 11
  • 73
  • 73
BMiner
  • 16,669
  • 12
  • 53
  • 53
9
if 'username' in this
    p=username

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

avoid3d
  • 620
  • 6
  • 12
6

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. :)

Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
  • 2
    Thanks, though FYI for express 3.x this is now `app.locals({ username: false });` – 7zark7 Nov 09 '13 at 10:03
  • 6
    Nice approach. Note that in Express 4.x `app.locals` is not a function anymore so it should be `app.locals.username = false;` – Tom May 12 '14 at 12:02
1

Even simpler with pug, the successor to jade

if msg
  p= msg
I Like
  • 1,711
  • 2
  • 27
  • 52
0

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();
};
Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206
0

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

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

TK-421
  • 10,598
  • 3
  • 38
  • 34