jaredhanson / connect-flash

Flash message middleware for Connect and Express.
MIT License
1.24k stars 158 forks source link

Wrong example checking for message #16

Open ePirat opened 10 years ago

ePirat commented 10 years ago

The examples show that this if (message) { is the proper way to check if a message is there, actually this will be true every time, even if no message is set. It seems to work with:

if (message.length !== 0) {

I am not sure, but it seems that message, when empty is an empty object ({}) so checking for it will be true in any case.

pronebird commented 10 years ago

I think it always returns array.

isimmons commented 9 years ago

Same here. If in your route or render method you set messages variable like

messages: req.flash()

Then you will get a messages variable in the rendered view which will be eqal to

{[]}

because req.flash() will still create an empty array.

So yes in your view you will need to check the length is not 0

I made a partial for flash messages that checks for both the existence and the length so I can include it at the top of all views

<% if(typeof messages !== 'undefined') { %>
<% if (typeof messages.error !== 'undefined' && messages.error.length > 0) { %>
    <p class="error"><%= messages.error %></p>
<% } %>
<% if (typeof messages.info !== 'undefined' && messages.info.length > 0) { %>
    <p class="info"><%= messages.info %></p>
<% } %>
<% if (typeof messages.success !== 'undefined' && messages.success.length > 0) { %>
    <p class="info"><%= messages.success %></p>
<% } %>
<% } %>

For ejs templates at top of body

<% include partials/flash.server.partial.html %>

This way I can just use req.flash() in my render function and every view will check for the existence of the 3 types of error messages I might or might not have flashed at some point in the process.