I have a simple page with head, menu, content and footer. I need to divide them into separate files. After reading through express documentation i (created 4 templates and) wrote something like this:
app.get('/', function(req, res) {
var response = [null, null, null, null]
, everyNotNull = function(elem) {
return (elem !== null);
}, sendResponse = function(type, str) {
switch (type) {
case 'head' : response[0] = str; break;
case 'menu' : response[1] = str; break;
case 'content' : response[2] = str; break;
case 'footer' : response[3] = str; break;
}
if (response.every(everyNotNull)) {
res.send(response.join(''));
}
};
res.partial('head', {'title' : 'page title'}, function(err, str) {
sendResponse('head', str);
});
res.partial('menu', {'active' : '/'}, function(err, str) {
sendResponse('menu', str);
});
res.partial('index', {'title' : 'Home'}, function(err, str) {
sendResponse('content', str);
});
res.partial('footer', {'nowdate' : (new Date()).getFullYear()}, function(err, str) {
sendResponse('footer', str);
});
});
Though it works it seems a bit dirty to me. Is there a better way to use partial templates?
You were right to suspect something was missing, you're doing unnecessary work there.
Express will stitch the templates together for you, just call res.render() and the name of the view you want to call. The layout and partials should get pulled in automatically.
In my apps I usually use partials as below. Just replace references to EJS with whichever template engine you're using (Jade, moustache, etc):
./lib/app.js
app.get('/', function(req, res) {
var model = {
layout:'customLayout', // defaults to layout.(ejs|jade|whatever)
locals:{
foo:'bar'
}
};
res.render('index',model);
});
./views/layout.ejs
<html>
<head><%- partial('partials/head') %></head>
<body>
<%- partial('partials/menu') %>
<%- body %>
<%- partial('partials/footer') %>
</body>
</html>
./views/index.ejs
<h1>Index page</h1>
./views/partials/menu.ejs
<div><a href='... </div>
./views/partials/head.ejs
<script>...</script>
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With