Tech Team
Tech Team

Reputation: 119

How do I use req.flash() with nunjucks?

I am using connect-flash to pass the flash message. In my controller, I am using the following code if (!req.user) { req.flash("error_msg", "User not found !!"); return res.redirect(307, '/'); }

In my view, I tried

{{ error_message }}

{{ req.flash('error_message') }}

{{ req.flash.get('error_message') }}

But none of it works. What's the current syntax to parse the flash message in nunjucks ?

Upvotes: 1

Views: 532

Answers (4)

Bipin Maharjan
Bipin Maharjan

Reputation: 523

With connect-flash package, you cannot directly use req.flash in template engine. You need to add a middleware that adds the flash message to the res.locals which can be accessed in template rendering.

Here is a short code snippet.

// this part should be before all the request resolver.
// adding flash function to response locals
app.use((req,res,next)=>{
 res.locals.flash = (arg) => { return req.flash(arg) };
 next();
});

// request resolver
app.get("/",(req,res)=>{
 req.flash("info","show me");
 res.render("index.njk",{});
});

app.listen(8080,()=>{...})

In nunjucks file:

<h3>{{ flash("info") }}</h3>

Upvotes: 0

Krishnadas PC
Krishnadas PC

Reputation: 6539

If you are using express js and nunjucks as template this is what I have done

in app.js

const flash = require('express-flash');
app.use(flash());

in Routes/controller code


try {
        await User.deleteOne({_id:req.params._id}).exec()   
        req.flash("success_msg", "User deleted");           
        return res.redirect('/admin/users') 
}

in Layout or view file


 {% if messages.success_msg  %}
          <div class="alert alert-success" role="alert">
            {{ messages.success_msg }}
          </div>
        {% endif %} 

Upvotes: 2

Tech Team
Tech Team

Reputation: 119

For anyone facing the same problem you can access the variable using {{ req.session.flash.error_msg }}

Upvotes: 0

Kiran Suthar
Kiran Suthar

Reputation: 72

First of all you have to install "express-flash" and put below code in app.js

app.js

const flash = require('express-flash');

In Your Controller put below code when you want to pass message

req.flash('error_msg', "User not found !!");
        return res.redirect(307, '/');

Put below code in your view file where you want to display message

<% if (typeof messages.error_msg !='undefined') { %>
        <p class="error"><%= messages.error_msg %></p>
    <% } %>

Upvotes: 0

Related Questions