How to conditionally display variables with EJS

Short version: <%= user.name ? user.name : '' %>

When using EJS as a template language, it can be a bit of a mystery how to concisely display variables if and only if they are defined.

For example, if you have a form field that is pre-filled with data from the database, you usually don’t want to pre-fill with the string “undefined”. Rather, you’d like those fields left blank. This is a common situation when using Node.js with MongoDB and Mongoose, which can be friendly to missing fields, if only there were an easy way to avoid the “undefined” value when rendering your EJS template.

Typical solutions have something awkward like

<% if(user.name) { %> <%= user.name %> <% } %>

That’s got all those extra %> terms.

You might try something like

<%= if(user.name) { user.name }%>

But that doesn’t like the “if”, because <%= is expecting a value, not a statement. So you might try this:

<% if(user.name) { user.name }%>

Which probably evaluates user.name rather than displaying it. Not only is that an ugly security risk (going straight from user data in your DB to code), it doesn’t actually output anything to the web page.

Fortunately, the ternary operator is magic. It can perform a conditional anywhere a value is needed.

Here’s the ternary for displaying EJS values only when defined:

<%= user.name ? user.name : '' %>

Yes, you need the final ”, but that’s a small price to pay.

Now, whenever you want to drop in a field value if–and only if–it is defined, use this trick.

For those sticklers out there, user.name could be defined but null or an empty string. The “technical” way to check for undefined would give us something like

<%= typeof user.name!='undefined' ? user.name : '' %>

But functionally, both approaches give you what you want for the form field use case. So, I’ll stick with the simpler, shorter one.

This entry was posted in coding, Development and tagged , , , , . Bookmark the permalink.

Leave a Reply