Question

I'm simply trying to display a value in an input field with Jade (0.20.3) and Express (2.5.8):

input(name='username', type='text', id="username", value=username)

It is quite simple, but this throws an error when the value is undefined:

username is not defined

However, the documentation indicates:

When a value is undefined or null the attribute is not added, so this is fine, it will not compile 'something="null"'.

Is there something that I would have done wrong?

Was it helpful?

Solution

Short answer: use locals.someVar if you're not sure that someVar exists.

Longer Answer:

I think that Brandon's initial answer and last comment are correct (though the #{...} syntax isn't needed), but to elaborate a bit: There's a difference between passing in an a variable (technically, an object property) with a value of undefined, and not passing that variable at all.

Because Jade transforms your template into JS source and evals it (in the context of a with block), you have to make sure that you're not referring to any variables that haven't been passed in, or they'll be . This blog post has some background on undefined vs undeclared variables and ReferenceError.

Your Jade template should work correctly if you do one of these things:

// ok, even if req.session.username is not defined
res.render('index', { username: req.session.username })

// ditto
res.local('username', req.session.username);
res.render('index')

But these won't work:

res.locals(req.session) //if no username property exists
res.render('index', { /* no username */ } )

If it's not practical to manually pass in each parameter you might want to refer to, you can refer to the variable in your template as properties on the locals object (e.g. locals.username)

OTHER TIPS

You have to make sure you're passing username into the Jade template. Example:

app.get('/', function (req, res) {
    res.render('index', { title:'APP NAME', username: req.session.username });
});

Also, you would call it like this in the Jade template: #{username}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top