Express & jade (node.js) - variable not defined when checking for availability

I get a pretty dumb error in an extremely simple express application. I use jade as a viewer, I say this just in case this is due to a problem.

I am trying to check if a variable is defined to visualize an object, but just checking this variable causes "variable not defined". Error. This is not the behavior that I expect, so I'm curious that 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 should be a way to check the variables on the views .: - /

EDIT: Forgot to say in which line the error is triggered, it is triggered in the second line "- if (user)".

+4
source share
3 answers

As mentioned in another Public API answer in the Jade section, the documentation says that the locals variable is how the data is passed to the Jade template. In a lark, I added variables to the jade pattern using locals . This correctly circumvents the error.

So, the following Jade template should solve your error:

 h1= title - if (locals.user) p Welcome to #{title}, #{user.username} - else p Welcome to #{title} 
+13
source

You have not concluded p Welcome to #{title}; #{user.username} p Welcome to #{title}; #{user.username} in quotation marks

try

 if(typeof obj != 'undefined') 
+3
source

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.

+1
source

Source: https://habr.com/ru/post/1413833/


All Articles