Santhoshkumar
Santhoshkumar

Reputation: 780

How to conditionally display HTML with EJS Template?

I tried following condition that's works fine,

<% if (user) { %>
  <h1> Success </h1>
<% } else { %>
  <h1> Failure </h1>
 <% } %>

but I want to check the condition like below,

<% if (user.verified == true ) { %>
  <h1> Success </h1>
<% } else { %>
  <h1> Failure </h1>
 <% } %>

Its not working, showing error. Please anyone help me to fix the issue.

Upvotes: 4

Views: 6651

Answers (2)

Ashutosh Tiwari
Ashutosh Tiwari

Reputation: 1597

Finally, I got a solution !!

<% if(typeof (user) != "undefined"){ %>
        <h1>User Exists</h1>
<% } %>

Mind that undefined is placed inside " " (quotes).

Just FYI :

Undefined, null, "" (empty string) are considered as a false in Javascript but still here I was getting error due to undefined in ejs file.

Hope that helps !

Upvotes: 2

ducdhm
ducdhm

Reputation: 1952

You need to check user is undefined or not. So the code should be:

<% if (user && user.verified == true) { %>
  <h1> Success </h1>
<% } else { %>
  <h1> Failure </h1>
<% } %>

Upvotes: 4

Related Questions