如何在Node的.dust文件上使用connect-flash和express-messages显示消息 [英] How to display message using connect-flash and express-messages on .dust file on Node

查看:34
本文介绍了如何在Node的.dust文件上使用connect-flash和express-messages显示消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Nodejs Expressjs Kraken ,在索引上添加产品时需要显示消息,但是我尝试了很多次用于配置,但消息仍未如我所愿.这是我的config.js:

I'm using Nodejs and Expressjs and Kraken, I need to display message when added a product on index but I tried many time for to config but messages still not appear as I expect. Here is my config.js:

var flash = require('connect-flash');
app = module.exports = express();
app.use(kraken(options));
//flash
app.use(flash());
app.use(function (req, res, next) {
   res.locals.messages = require('express-messages')(req, res);
   next();
});

我的控制器:

router.post('/somePath', function (req, res) {
//something to do to add
res.flash('messages','Add success!!')
res.render('path/index');
});

我的index.dust文件:

`{>"layouts/master" /} 
 {<body}
   {messages|s}
   // body goes here
 {/body}

`

推荐答案

您已经很接近答案了.

此行

   res.locals.messages = require('express-messages')(req, res);

messages 中存储一个函数,该函数将Flash消息作为html片段输出.

Stores a function in messages that outputs the flash messages as an html fragment.

res.locals 通过express与用于渲染模板的模型合并.

res.locals is merged by express with the models that are used to render your template.

现在,您只需要一种从尘埃模板中调用此功能的方法.

Now you just need a way to invoke this function from within the dust template.

这样做:

{messages|s}

实际上并没有调用该函数.您需要像它是上下文帮助程序一样对其进行调用:

Doesn't actually invoke the function. You need to call it as if it were a context helper:

{#messages /}

您将要清除的最后一个障碍. express-messages 期望的功能签名与尘土提供的功能签名不同,因此您必须将其包装在一个辅助函数中(在server.js文件中):

You'll have one last hurdle to clear. The function signature that express-messages expects, is different from what dust provides, so you'll have to wrap it within a helper function (in your server.js file):

app.use(flash());
app.use(function (req, res, next) {
    var messages = require('express-messages')(req, res);
    res.locals.messages = function (chunk, context, bodies, params) {
        return chunk.write(messages());
    };
    next();
});

这篇关于如何在Node的.dust文件上使用connect-flash和express-messages显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆