2

I am trying to pass a message object to a template using ejs. My route code is as follows:

app.get('/', function(req, res) {
    res.render('index.ejs', {message: 'A message'});
});

In my ejs (index.ejs) file, I have:

    <% if (message) { %>
        <div class="alert alert-danger"><%= message %></div>
    <% } %>

But when I do not pass an object at all (not just message: "") it returns the following error:

ReferenceError: /Users/Documents/node/views/index.ejs:13
    11| <body>
    12|     <div class="container">
 >> 13|         <% if (message) { %>
    14|             <div class="alert alert-danger"><%= message %></div>
    15|         <% } %>
    16|         <div class="jumbotron text-center">

message is not defined

Similarly, if I try if(message.length > 0) but that just gives me the same error. I thought the whole point of an if statement would be that the if message doesn't exist, it just skips. How can I just make ejs render nothing if the message object is not passed or do I have to pass an empty message obect each time?

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
Startec
  • 12,496
  • 23
  • 93
  • 160
  • I am sorry, I don't understand. Passing no object results in that error. I would prefer to not have to pass an object with an empty string each time... – Startec Nov 04 '14 at 22:43
  • 1
    You could try using ```locals.message```, as it's shown in http://stackoverflow.com/questions/7289916/how-would-you-check-for-undefined-property-in-ejs-for-node-js – ffflabs Nov 04 '14 at 22:43

1 Answers1

5

Explicitly check whether or not message is defined. This fixes it:

<% if (typeof message !== 'undefined' && message.length > 0) { %>
  <div class="alert-danger"><%= message %></div>
<% } %>
twhitehead
  • 81
  • 2
  • 6