More work on mvc example

This commit is contained in:
Tj Holowaychuk 2010-08-20 17:08:10 -07:00
parent 9231245a3f
commit 20c5892f9a
7 changed files with 53 additions and 5 deletions

View File

@ -1,9 +1,9 @@
module.exports = {
// /users
// /
index: function(req, res){
res.render('index');
res.render();
}
};

View File

@ -11,7 +11,7 @@ module.exports = {
// /users
index: function(req, res){
res.send('users: ' + JSON.stringify(users));
res.render(users);
},
// /users/:id
@ -20,7 +20,7 @@ module.exports = {
var id = req.params.id,
user = users[id];
if (user) {
res.send('user: ' + JSON.stringify(user));
res.render(user);
} else {
next(new Error('User ' + id + ' does not exist'));
}

View File

@ -27,8 +27,14 @@ function bootController(app, file) {
actions = require('./controllers/' + name),
plural = name + 's', // realistically we would use an inflection lib
prefix = '/' + plural;
// Special case for "app"
if (name == 'app') {
prefix = '/';
}
Object.keys(actions).map(function(action){
var fn = actions[action];
var fn = controllerAction(name, plural, action, actions[action]);
switch(action) {
case 'index':
app.get(prefix, fn);
@ -53,4 +59,26 @@ function bootController(app, file) {
break;
}
});
}
// Proxy res.render() to add some magic
function controllerAction(name, plural, action, fn) {
return function(req, res, next){
var render = res.render,
path = __dirname + '/views/' + name + '/' + action + '.ejs';
res.render = function(obj, options, fn){
res.render = render;
options = options || {};
options.locals = options.locals || {};
// Expose obj as the "users" or "user" local
if (action == 'index') {
options.locals[plural] = obj;
} else {
options.locals[name] = obj;
}
return res.render(path, options, fn);
};
fn.apply(this, arguments);
};
}

View File

@ -0,0 +1,5 @@
<h1>Application Index</h1>
<p>Try visiting one of the following urls:</p>
<ul>
<li><a href="/users">/users</a></li>
</ul>

View File

@ -0,0 +1,8 @@
<html>
<head>
<title>Express - MVC Example</title>
</head>
<body>
<%- body %>
</body>
</html>

View File

@ -0,0 +1,6 @@
<h1>Users</h1>
<ul>
<% users.forEach(function(user){ %>
<li><%- user.name %></li>
<% }) %>
</ul>

View File

@ -0,0 +1 @@
<h1>Viewing user <%- user.name %></h1>