4

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

3 Answers 3

13

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}
Sign up to request clarification or add additional context in comments.

Comments

3

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

try

if(typeof obj != 'undefined')

1 Comment

This does work, thanks!. I still think the simple check should work though, it is much cleaner :-(.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.