Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express & jade (node.js) - variable is not defined error when checking for existence

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

like image 367
uorbe001 Avatar asked Dec 04 '22 03:12

uorbe001


2 Answers

As 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}
like image 134
Jade Avatar answered Dec 24 '22 08:12

Jade


You didn't enclose p Welcome to #{title}; #{user.username} in quotes

try

if(typeof obj != 'undefined')
like image 31
PitaJ Avatar answered Dec 24 '22 07:12

PitaJ