I'm trying to made a crude store front app in Express and im trying to set it up so that if a person is logged in so the username is not 'undefined', it shows one block, and if you're logged out it shows another.
Here's my layout.jade file:
doctype 5
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
h1.main= title
body
- if (typeof(username) !== 'undefined') {
block items
-}
- else {
block content
-}
My content block contents.
extends layout
block content
#content
img#splash(src='images/ninja.png')
And my items block.
block items
#items
h1 Hello (username)
When I log in, I just see the pages title (my layout.jade files contents) and not the content of the items.jade file.
Does anyone know why this is? I'm new to Express and can't work it out :/
If I do something like.
- if (typeof(username) !== 'undefined') {
p test
-}
- else {
block content
-}
Then I can see the text upon logging in.
Your code is correct but are you passing username when rendering the jade file. jade is rendered by your express server in return to a request and if else code is executed when rendering happens.
If you login (set username) or logout after the page is displayed then the block will not be displayed/updated. In your app, you can pass the username while rendering
res.render('layout', {locals:{title: 'Page title', username: "something"}});
//display block content
res.render('layout', {locals:{title: 'Page title'}});
//display block items
Use underscore.Js To better manage and map html to Jade, it's best to functions
In the file config express or connect
app.use(function(req, res, next){
res.locals._ = require('underscore');
next();
});
In index.jade
doctype 5
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
h1.main= title
body
if _.isUndefined( username )
//- if _.isString( username ) or bla...
block items
else
block content
It is much better, and you can do interesting things!