Obecnie używam Jade w nowym projekcie. Chcę wyrenderować stronę i sprawdzić, czy jest dostępna określona zmienna.
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?
Odpowiedzi:
This should work:
- if (typeof(username) !== 'undefined'){ //-do something -}
źródło
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.źródło
render
stage:res.render('view', {username: user.name});
if 'username' in this p=username
This works because res.locals is the root object in the template.
źródło
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. :)źródło
app.locals({ username: false });
app.locals
is not a function anymore so it should beapp.locals.username = false;
Shouldn't 'username' be included in the locals object?
https://github.com/visionmedia/jade/tree/master/examples
źródło
undefined
if it's checked withif
beforehand.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(); };
źródło