Skip to content

Instantly share code, notes, and snippets.

@lbeschastny
Last active August 29, 2015 13:55
Show Gist options
  • Save lbeschastny/8687591 to your computer and use it in GitHub Desktop.
Save lbeschastny/8687591 to your computer and use it in GitHub Desktop.
var express = require('express');
var app = module.exports = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname);
app.set('view engine', 'html');
// application level variables
app.locals.title = "EJS example";
app.locals.header = "Some users";
// request level variables
app.use(function (req, res, next) {
// using setTimeout to emulate async call to DB
setTimeout(function() {
res.locals.users = [
{ name: 'tobi', email: 'tobi@example.com' },
{ name: 'loki', email: 'loki@example.com' },
{ name: 'jane', email: 'jane@example.com' }
];
next();
}, 1000);
});
app.get('/', function(req, res){
// both app.locals and res.locals are available to ejs egine
res.render('index');
});
if (!module.parent) {
app.listen(3000);
console.log('Express app started on port 3000');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> <%= title %> </title>
<style type="text/css">
body {
padding: 50px;
font: 13px Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<h1><%= header %></h1>
<ul id="users">
<% users.forEach(function(user){ %>
<li><%= user.name %> &lt;<%= user.email %>&gt;</li>
<% }) %>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment