Jade - Silnik szablonów: Jak sprawdzić, czy istnieje zmienna

80

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?

mbecker
źródło
1
seems by now (2014), we no longer get this error. Much easier to use.
gfaceless

Odpowiedzi:

105

This should work:

- if (typeof(username) !== 'undefined'){
  //-do something
-}
Chetan
źródło
- if (isset(username))' isset is not defined
mbecker
2
Sorry, I got confused with PHP and Javascript. Updated my answer.
Chetan
7
Tanks a lot! This Code works: - if (typeof username !== "undefined")
mbecker
93

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.

BMiner
źródło
This gives me a compiler error : 'builtin_function_or_method' object has no attribute 'username'
zakdances
@yourfriendzak - Are you sure your error is caused by this portion of your template?
BMiner
1
Works perfect and it's better than using inline javascript, thanks.
Sergi Ramón
I like this answer because this shows that Jade is whitespace sensitive language.
Victor.Palyvoda
Careful this will only work if the variable was defined in the controller at the render stage: res.render('view', {username: user.name});
Augustin Riedinger
10
if 'username' in this
    p=username

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

avoid3d
źródło
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
źródło
2
Thanks, though FYI for express 3.x this is now app.locals({ username: false });
7zark7
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
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
źródło