Created
December 28, 2015 01:09
-
-
Save CaptainYarb/21b4d3a9f4eb5b5a5960 to your computer and use it in GitHub Desktop.
Express EJS Templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ejs = require('ejs'), | |
_ = require('lodash'); | |
var util = require('util'); | |
app.engine('ejs', ejs.renderFile); | |
app.set('view engine', 'ejs'); | |
app.set('views', '/path/to/templates'); | |
app.use(function(req, res, next){ | |
res.view = function(templateFile, data){ | |
data = data || {}; | |
// attach URL params to array | |
if(!data.params){ | |
data.params = req.path.split('/'); | |
data.params.splice(0, 1); | |
if(data.params[0] === ''){ | |
data.params[0] = '/'; | |
} | |
} | |
data.user = req.user || null; | |
// actually handle the view | |
data = _.defaults(data, config.website.template.data); // merge defaults from config | |
data._global = data; // extend variables so they are available on layouts AND templates | |
var layout = util.format('layouts/%s.ejs', data.layout), | |
template = util.format('%s/%s.ejs', app._views, templateFile); | |
// ignore templates | |
if(data.noTemplate){ | |
return res.render(template, data); | |
} | |
// setup templates | |
ejs.renderFile(template, data, function(err, results){ | |
if(err){ | |
return next(err); | |
} | |
data.content = String(results); | |
return res.render(layout, data); | |
}); | |
}; | |
return next(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hello, <% user.name %> | |
<%- include('widgets/profile', _global) -%> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="x-ua-compatible" content="ie=edge"> | |
<title><%= title %></title> | |
</head> | |
<body> | |
<%- content %> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment