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

node.jsPugExpress

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

This should work:

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

Solution 2 - node.js

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.

Solution 3 - node.js

if 'username' in this
    p=username

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

Solution 4 - node.js

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

Solution 5 - node.js

Even simpler with pug, the successor to jade

if msg
  p= msg

Solution 6 - node.js

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

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

Solution 7 - node.js

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();
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmbeckerView Question on Stackoverflow
Solution 1 - node.jsChetanView Answer on Stackoverflow
Solution 2 - node.jsBMinerView Answer on Stackoverflow
Solution 3 - node.jsavoid3dView Answer on Stackoverflow
Solution 4 - node.jsDominic BarnesView Answer on Stackoverflow
Solution 5 - node.jsI LikeView Answer on Stackoverflow
Solution 6 - node.jsTK-421View Answer on Stackoverflow
Solution 7 - node.jsAugustin RiedingerView Answer on Stackoverflow