Skip to content

Instantly share code, notes, and snippets.

@Juriy
Last active December 30, 2015 00:09
Show Gist options
  • Save Juriy/7747820 to your computer and use it in GitHub Desktop.
Save Juriy/7747820 to your computer and use it in GitHub Desktop.
Views example in node.js
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(function(req, res, next) {
console.log("Serving " + req.method + ":"
+ req.url);
if (req.url == "/err") {
foo.bar = 'Can\'t be!';
}
next();
});
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: "mysecret"}));
app.get("/ejs", function(req, res) {
res.render('list', {
names: ['john', 'pete'],
layout: false
});
});
app.use(express.static(__dirname + "/public"));
// user/123
app.get("/user", function(req, res) {
if (!req.session.user) {
res.send("No user in session");
req.session.user = "PETE";
} else {
res.send("You are " + req.session.user);
}
});
app.listen(80);
console.log("listening 80");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>Views demo</h1>
<div class="board">
<ul>
<!-- EJS -->
<% for (var i = 0; i < names.length; i++) { %>
<li><%= names[i] %></li>
<%} %>
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment