How can I access req and res in layout.ejs

3,241 views
Skip to first unread message

nightwolfz

unread,
May 24, 2011, 2:57:00 PM5/24/11
to Express
First of all, sorry for such a beginners question. I'm using ejs
templating with expressJS and I'd like to have some simple logic in my
layout page.

<html>
<head>
<title>Test</title>
</head>
<body>

<div id="top">
<%
if (req.session.username){
%>
<form method="post" action="/login">
<input type="text" name="login[username]" value="username">
<input type="text" name="login[password]" value="aaaaaa">
<button>Login</button>
</form>
<% } %>
</div>
<div id="wrapper">
<%- body %>
</div>
</body>
</html>
================================

But req object is empty. What should I do ?

My config:
================================
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'coolCat' }));
app.use(express.compiler({ src: __dirname + '/public', enable:
['less'] }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

Charlie

unread,
May 24, 2011, 6:55:02 PM5/24/11
to Express
How are you calling the view? You pass variables to the template like
this:

app.get('/', function(req, res) {
res.render('index.ejs', {
req: req,
foo: 'bar'
});
});

nightwolfz

unread,
May 25, 2011, 6:24:49 AM5/25/11
to Express
I know, it works with views, but I don't know how to pass them to the
layout file.

Josh Chaney

unread,
May 25, 2011, 6:41:45 AM5/25/11
to expre...@googlegroups.com
The locals are passed to both the layout and your view.

app.get('/', function(req, res) {
res.render('index.ejs', {
title: 'My awesome website'
});
});

and in your layout you would do something like:

<head>
    <title><%= title %></title>
</head>

and it can also be accessed in your view:

<div id="container">
<h2>Welcome to <%= title %></h2>
</div>

I apologize if that's not the right syntax for EJS.. I'm a Jade man, myself. :)

-- 
Josh Chaney

--
You received this message because you are subscribed to the Google Groups "Express" group.
To post to this group, send email to expre...@googlegroups.com.
To unsubscribe from this group, send email to express-js+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/express-js?hl=en.

Reply all
Reply to author
Forward
0 new messages