Startec
Startec

Reputation: 13206

EJS and Node, EJS throws an error if passed in object does not exist?

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?

Upvotes: 2

Views: 3522

Answers (1)

twhitehead
twhitehead

Reputation: 81

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

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

Upvotes: 5

Related Questions