Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Ternary Operator in EJS

<%- user ?  '<h1>Hello  user.name  </h1>' : '<h1>Hello Guest</h1>'  %>

The user.name is a variable, but when i load the page it will be showing user.name instead of the value the user.name contained.

like image 319
Tijani Eneye Avatar asked Sep 18 '25 05:09

Tijani Eneye


2 Answers

You have two mistakes here:

  1. You use <%=, which does not escape html, which can lead to xss.
  2. You're not actually embedding the variable user.name in your strings, it's just the text.

Since having unnecessary unescaped HTML can lead to XSS, the best way is to move the h1 out of the string and use template strings to embed the name:

<h1><%= user ? `Hello ${user.name}` : 'Hello Guest' %></h1>
like image 78
Aplet123 Avatar answered Sep 19 '25 19:09

Aplet123


Almost spot-on. Substituting the ternary's left-hand "if" result to use concatenation for user.name should do the trick, so it reads that as a dynamic value rather than plain text.

You may also want to check to ensure the name property exists in the user and that it has a non-empty, non-whitespace value.

Try this:

<%- user?.name && user.name.trim().length ? '<h1>Hello ' + user.name.trim() + '</h1>' : '<h1>Hello Guest</h1>' %>

You could also utilize template literals if you prefer it to concatenation:

<%- user?.name && user.name.trim().length ? `<h1>Hello ${user.name.trim()}</h1>` : '<h1>Hello Guest</h1>' %>

A couple of notes:

  • ?. is called optional chaining, allowing you to check to see if a property exists within an object variable while preventing any error from being fired if the object doesn't exist.

  • I'm using .trim() here to ensure that the value is not only not empty, but also that it contains non-whitespace characters by trimming all leading and trailing whitespace from the string if it exists and then checking to make sure the length of the string is still greater than zero using .length. We don't need to check if .length > 0 since 0 is a falsy value already. If the conditions evaluate to true, we also output the trimmed value in the left-hand result of the ternary.

Perhaps best of all, you can move some of the HTML outside the JS statement to keep the code as concise as possible:

<h1>Hello <%- user?.name?.trim()?.length ? user.name.trim() : 'Guest' %></h1>
like image 42
Brandon McConnell Avatar answered Sep 19 '25 20:09

Brandon McConnell