Search code examples
javascriptnode.jsexpresspugconnect-flash

How can i fix divs from connect-flash, they are allways active(i am using pug)?


So i have this in my app.js: var flash = require('connect-flash');

app.use(flash());
app.use(function(req , res , next){
  res.locals.success_messages = req.flash('success');
  res.locals.error_messages = req.flash('error');
  next();
});

In my layout.pug i have:(right before block content)

if success_messages 
        .alert.alert-success=success_messages
if error_messages
        .alert.alert-danger=error_messages

And when i use it :

req.flash('error','All fields required!');

and success.

But div(class="alert alert-danger") and div(class="alert alert-success") are allways on the top on my page with no messages, just 2 empty bars. Divs Whats wrong ?


Solution

  • This is going to happen when the variables success_messages and error_messages are truthy. Note from the MDN documentation that empty arrays and empty objects are still going to evaluate as true in an if statement.

    In your route add these two lines and you'll see exactly what you are passing into the template. If it looks like [] or {} then the if statement in pug will pass the truthy test and those divs will render blanks.

    console.log( 'success_messages is ' + JSON.stringify(success_messages) );
    console.log( 'error_messages is ' + JSON.stringify(error_messages) );
    

    You can fix this by adding a length test in the template (I am assuming you're getting an array from connect-flash):

    if success_messages.length > 0 
      .alert.alert-success=success_messages
    if error_messages.length > 0
      .alert.alert-danger=error_messages
    

    This is an explicit test and doesn't fall back to truthiness which can sometimes give unexpected results.