Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong example checking for message #16

Open
ePirat opened this issue Aug 26, 2014 · 2 comments
Open

Wrong example checking for message #16

ePirat opened this issue Aug 26, 2014 · 2 comments

Comments

@ePirat
Copy link

ePirat commented Aug 26, 2014

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
Copy link

I think it always returns array.

@isimmons
Copy link

isimmons commented Jul 6, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants