app.js
This file
Path
examples/flash/app.js
74 lines · 2.2 KiB · JavaScript
Last changed by
Added another dynamicHelper example to flash exampleTj Holowaychukbefore adoptionfd9a245
History of this fileTake it
Merge branch 'flash-example'Tj Holowaychukbefore adoption7dff9dd
lines 1–28why, one step back12/**3 * Module dependencies.4 */56var express = require('../../lib/express');78// App with session support910var app = express.createServer(11 express.cookieDecoder(),12 express.session()13);1415// View settings1617app.set('views', __dirname + '/views');18app.set('view engine', 'ejs');1920// Dynamic helpers are functions which are executed21// on each view render, unless dynamicHelpers is false.2223// So for example we do not need to call messages() in our24// template, "messages" will be populated with the return25// value of this function.2627app.dynamicHelpers({28 messages: function(req, res){Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 29–52why, one step back29 // In the case of flash messages30 // we return a function, allowing31 // flash messages to only be flushed32 // when called, otherwise every request33 // will flush flash messages regardless.34 return function(){35 // Grab the flash messages36 var messages = req.flash();37 // We will render the "messages.ejs" partial38 return res.partial('messages', {39 // Our target object is our messages40 object: messages,41 // We want it to be named "types" in the partial42 // since they are keyed like this:43 // { info: ['foo'], error: ['bar']}44 as: 'types',45 // Pass a local named "hasMessages" so we can easily46 // check if we have any messages at all47 locals: { hasMessages: Object.keys(messages).length },48 // We dont want dynamicHelpers in this partial, as49 // it would cause infinite recursion50 dynamicHelpers: false51 });52 }Merge branch 'flash-example'Tj Holowaychukbefore adoption7dff9dd
lines 53–55why, one step back53 }54});55Added another dynamicHelper example to flash exampleTj Holowaychukbefore adoptionfd9a245
lines 56–65why, one step back56app.dynamicHelpers({57 // Another dynamic helper example. Since dynamic58 // helpers resolve at view rendering time, we can59 // "inject" the "page" local variable per request60 // providing us with the request url.61 page: function(req, res){62 return req.url;63 } 64});65Merge branch 'flash-example'Tj Holowaychukbefore adoption7dff9dd
lines 66–74why, one step back66app.get('/', function(req, res){67 // Not very realistic notifications but illustrates usage68 req.flash('info', 'email queued');69 req.flash('info', 'email sent');70 req.flash('error', 'delivery failed');71 res.render('index');72});7374app.listen(3000);