DEV Community

Paul Walker
Paul Walker

Posted on • Originally published at solarwinter.net on

Optional values in EJS templates

For my current tinkering project I'm using EJS with hapi. Up until now I've been writing front-end code with Vue (or occasionally Svelte) with an Express back-end, so this is a change for me. There are downsides but definite upsides - I'll try and write about those another time.

In the meantime, one difference I found is how they handle optional values. In the case of (for example) Vue a v-if handles both undefined and "falsy" values.

<router-link v-if="!loggedIn" to="/register">Register | </router-link>

Enter fullscreen mode Exit fullscreen mode

But that doesn't work for EJS - the equivalent template throws an error:

$ cat test.ejs
<% if (message) { %>
  <h3><%= message %></h3>
<% } %>

$ npx ejs ./test.ejs
ReferenceError: ejs:1
 >> 1| <% if (message) { %>
    2| <h3>Message: <%= message %></h3>
    3| <% } %>
    4|

message is not defined

Enter fullscreen mode Exit fullscreen mode

Instead, what you need to do is check for locals.message:

<% if (locals.message) { %>
  <h3><%= locals.message %></h3>
<% } %>
Enter fullscreen mode Exit fullscreen mode

and all is well, both with no value and with a value:

$ npx ejs ./test.ejs

$ npx ejs ./test.ejs message="Hello world"
<h3>Message: Hello world</h3>

Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay