jaredhanson / connect-flash

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

Success & Error Flashes #20

Open Scribblets opened 9 years ago

Scribblets commented 9 years ago

On a particular page, I want to have a flash for both success and error messages. However, I cannot figure out how to determine which is which in the view template:

request.flash('success', message);
request.flash('error', message);

How to access the message in the view: <%= message %>

if(message.error) {
     // Show error state
} else if(message.success) {
     // Show success state
}

But I'm not seeing any way to do this? Is this possible?

mrmanicou commented 9 years ago

In your handler you specify the object to create that message variable that you send to the view. Like so: ...
response.render('view', {message:{success: request.flash('success'),error: request.flash('error')}});

isimmons commented 9 years ago

Makes for some extra work because in your view you have to check if the array is empty. Doing it the above suggested way, if you don't have any success type errors you will still get

console.log(messages);
//output
{success: [], error: ['some error message', 'another error message']

You can also call request.flash() without specifying the type and get the same output

response.render('view', { messages:req.flash() })

Just playing around with this and had to do the following to retrieve messages in a ejs template

<% 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>
<% } %>

Gonna see if I can figure out a good helper function to create or just put this in it's own messages template to be included where ever I need it.