0

In a template I have a variable that I would like to display the value of but I would like it to be optional.

Here is what I have:

<h1>Title</h1>
<%= message %>

Then I use:

app.render("page.ejs"); 

But sometimes I use:

app.render("page.ejs", {message: "test"});

I end up getting this sometimes:

ReferenceError: /views/login.ejs:4
    2| <h1>Title</h1>
 >> 3|    <%- message %>

message is not defined

Is this an error on my part?

I have tried both:

<%- message %>
<%= message %>
<%= if (message) message %>  // SyntaxError: Unexpected token 'if' in 

Update
The linked question gave some answers. To get rid of the error this works:

 <%= locals.message %>

Or

 <%= locals?.message %>

This might also work:

 <%- locals?.message %>
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • 3
    Does this answer your question? [What is the proper way to check for existence of variable in an EJS template (using ExpressJS)?](https://stackoverflow.com/questions/5372559/what-is-the-proper-way-to-check-for-existence-of-variable-in-an-ejs-template-us), though id lean towards just doing `app.render("page.ejs", {message: ""});` else your end up with checks all over the view which it not its responsibility to check for undefined vars, just pass empty ones – Lawrence Cherone Apr 20 '23 at 17:32

1 Answers1

0

You are lucky, EJS allows you to write conditions and loops!

Currently, according to the error you receive, your message variable has never been defined, so make sure it is defined correctly.

Obviously, if, as in your case, you want a conditional display, you can use the native features of EJS.

So, you can use that:

<% if (locals.message) { %>
    <h1>Title</h1>
    <%= message %>
<% } else { %>
    <h1>Title</h1>
    No message for you...
<% } %>

You have the example here I think if you want: https://ejs.co/#docs

Otherwise, the variables are displayed with an equal sign. (<%= message %> and not <%- message %>)

All your data will be accessible both as variables (if any), and via the locals object which will always be present.

Pioupia
  • 339
  • 2
  • 15