I'm getting a pretty dumb error on a extremely simple express app. I am using jade as the view engine, I'm saying this just in case it is related to the problem.
I'm trying to check if a variable is defined in order to render one thing or another, but simply checking for that variable triggers a "variable is not defined" Error. This is not the behaviour I'd expect, so I'm wondering if I'm doing something wrong. This is the view code I'm using:
h1= title
- if (user)
p Welcome to #{title}, #{user.username}
- else
p Welcome to #{title}
What is the right way to do this? There must be a way to check for variables on the views. :-/
EDIT: Forgot to say on what line the error is triggered, it is triggered on the second line "- if (user)".
I'm getting a pretty dumb error on a extremely simple express app. I am using jade as the view engine, I'm saying this just in case it is related to the problem.
I'm trying to check if a variable is defined in order to render one thing or another, but simply checking for that variable triggers a "variable is not defined" Error. This is not the behaviour I'd expect, so I'm wondering if I'm doing something wrong. This is the view code I'm using:
h1= title
- if (user)
p Welcome to #{title}, #{user.username}
- else
p Welcome to #{title}
What is the right way to do this? There must be a way to check for variables on the views. :-/
EDIT: Forgot to say on what line the error is triggered, it is triggered on the second line "- if (user)".
Share Improve this question asked May 22, 2012 at 20:16 uorbe001uorbe001 1873 silver badges11 bronze badges3 Answers
Reset to default 13As is mentioned in another answer the Public API section of the Jade documentation says that the locals
variable is how data is passed to a Jade template. On a lark I prepended my variables in the jade template with locals
. This correctly bypassed the error.
So the following Jade template should resolve your error:
h1= title
- if (locals.user)
p Welcome to #{title}, #{user.username}
- else
p Welcome to #{title}
You didn't enclose p Welcome to #{title}; #{user.username}
in quotes
try
if(typeof obj != 'undefined')
layout.jade
# the following function is a safe getter/setter for locals
- function pagevar(key, value) { var undef; return (value===undef) ? locals[key] || null : locals[key] = value; }
block config
#intended as a non-rendered block so that locals can be overridden.
# put your defaults here... - use append in the child view
!!!
html
head
title=pagevar('title')
meta(name='description',content=pagevar('description'))
...
page.jade
append config
- locals.title = 'override';
- locals.description = 'override 2';
- pagevars('somekey', 'some value');
...
Easy peazy.