简体   繁体   中英

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.

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>

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>
<%= user ?  ('<h1>Hello ' + user.name + '</h1>') : '<h1>Hello Guest</h1>'  %>

You can have an empty user object or null user variable, so use below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM