In Express.js, how do I make my template display the flash messages?
app.get('/',function(req,res){
res.render('home'); // I want the template to be able to access the flash mes开发者_运维问答sage..
});
app.get('/go',function(req,res){
req.flash("info", "You went GO, and got redirected to home!");
res.redirect('/');
});
The user first goes to "/go". After that, he will be redirected to "/" and I want a flash message to show as a javascript alert.
How can I do that?
Add it as a local to your call to render:
res.render("home", {info: req.flash("info")});
And use it in your template:
#flash
p= info
You can use express dynamic helpers to make your life easier.
app.dynamicHelpers({flashMessages: function(req, res) {
var html = ""
, flash = req.flash();
['error', 'info'].forEach(function(type) {
if(flash[type]) {
flash[type].forEach(function(message) {
html += "<div class='alert " + type + "'>" + message + "</div>";
});
}
});
return html; }});
and in your layout (ejs example)
<body><%- flashMessages %><%- body %></body>
app.dynamicHelpers({flash: function(req, res){return req.flash();}});
Now you have access at the flash object in you view. No HTML in your logic and no need to add all the params in every routes.
For me, I use the following code to display flash message:
In app.js
app.use(function (req, res, next) {
req.session.message = req.session.message || { error: [], success: [], info: [] };
app.locals.message = req.session.message;
}
In your user.js route:
app.post('/users/new', function (req, res, next) {
//...
// do some work
req.session.message.info.push('Account created successfully');
res.redirect('/login');
});
Then, create a message.jade
in view that you could be included into other views:
In message.jade
- var i
- if (message.error && message.error.length)
.alert.alert-warning.alert-dismissable
button.close(type="button", data-dismiss="alert", aria-hidden="true") ×
- for (i = 0; i < message.error.length; i++)
.center!= message.error[i]
- if (message.info && message.info.length)
.alert.alert-info.alert-dismissable
button.close(type="button", data-dismiss="alert", aria-hidden="true") ×
- for (i = 0; i < message.info.length; i++)
.center!= message.info[i]
- message.info = message.error = [] // REMEMBER to reset messages to an empty array
Had a similar issue, solution seems to be:
req.flash('error', 'validation failed');
res.redirect('back');
Using back seems to maintain the flash message, where as redirecting to the same route looses it.
If you're using Express 3, the built-in flash functionality has been removed. To get the same functionality, you'll want to install the connect-flash
module, then add the code from this Gist just after you initialize your sessions and before app.use(app.router);
: https://gist.github.com/3070950
精彩评论