在Express.js中,如何使模板显示flash消息
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 message..
});
app.get('/go',function(req,res){
req.flash("info", "You went GO, and got redirected to home!");
res.redirect('/');
});
用户首先转到"/go"。之后,他将被重定向到"/",我想要一条闪烁消息显示为javascript警报。
我该怎么做?
将其作为本地添加到要渲染的调用中:
res.render("home", {info: req.flash("info")});
并在您的模板中使用它:
#flash
p= info
您可以使用express动态助手来简化您的生活。
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; }});
并且在您的布局中(ejs示例(
<body><%- flashMessages %><%- body %></body>
app.dynamicHelpers({flash: function(req, res){return req.flash();}});
现在,您可以访问视图中的flash对象。您的逻辑中没有HTML,也不需要在每条路由中添加所有参数。
对我来说,我使用以下代码来显示闪烁消息:
在app.js中
app.use(function (req, res, next) {
req.session.message = req.session.message || { error: [], success: [], info: [] };
app.locals.message = req.session.message;
}
在user.js路由中:
app.post('/users/new', function (req, res, next) {
//...
// do some work
req.session.message.info.push('Account created successfully');
res.redirect('/login');
});
然后,在视图中创建一个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
也有类似的问题,解决方案似乎是:
req.flash('error', 'validation failed');
res.redirect('back');
使用back似乎可以维护flash消息,因为重定向到相同的路由会丢失它。
如果您使用的是Express 3,则内置的闪存功能已被删除。要获得相同的功能,您需要安装connect-flash
模块,然后在初始化会话之后和app.use(app.router);
之前添加来自此Gist的代码:https://gist.github.com/3070950
相关文章:
- 设置显示后Flash对象方法不可用:无
- 字符串比较显示从flash[:alert]检索到的字符串上的错误
- Flash 消息在刷新或辅助发布之前不会显示
- 仅在禁用 Flash 时显示颜色框关闭按钮
- 基于 SWFObject 的 Flash 影片不会在 Internet Explorer 10 中显示
- 单击“保存到CSV”按钮后显示通知(如果未安装Flash Player)
- Plupload-在使用Flash Runtime且浏览器没有Flash时显示警告
- Fusion图表没有显示flash播放器警告信息
- 如何使用javascript显示/隐藏flash对象
- Flash消息-如何正确显示-RAILS/JS
- 如果启用了flash,则显示一个或另一个Drupal块
- 鼠标悬停时,会在不同的位置显示Flash动画
- 使用JavaScript函数显示flash
- 如何使用jQuery (SJR)在Rails上显示flash消息
- 在ruby on rails中显示flash错误信息后,javascript更改了样式
- jQuery加载PHP显示flash内容
- 在Express.js中,如何使模板显示flash消息
- 在提交轨道上的模式对话框中显示 Flash 消息
- 在显示flash消息时增加DOM膨胀
- 在Rails中显示flash通知的最佳方式