How to display message using connect-flash and express-messages on .dust file on Node

你。 提交于 2021-02-08 10:09:28

问题


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();
});

My controller :

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

My index.dust file:

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

`


回答1:


You're pretty close to the answer.

This line

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

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

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.

Doing this:

{messages|s}

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

{#messages /}

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();
});


来源:https://stackoverflow.com/questions/39829177/how-to-display-message-using-connect-flash-and-express-messages-on-dust-file-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!