I used EJS layout in my Node.js application. Currently I faced a problem when data which is required in the EJS file is not available then it simply generate an error. What I want is to add a condition before using the EJS variable in javascript.
Here is my code in which I use EJS variable inside script tag.
button.addEventListener("click",function() { //here i face an error when sessionID is not available stripe.redirectToCheckout({ sessionId:'<%= sessionId %>' }) })
here is the code in which I use conditions inside the EJS.
<div class="col-md-4 offset-md-4"> <%if (data) { %> <h2><%- data.name %></h2> <h3><%- data.cost %></h3> <p><%- sessionId %></p> <button id="stripe-button" type="button" class="btn btn-info">Purchase</button> <% } %> <%if (message) { %> <h2><%- message %></h2> <% } %> </div>
It also shows an error when it do not receive any message variable.
Error which I received is:
message is not defined. sessionID is not defined.
Advertisement
Answer
Your if check is incorrect. You can check locals.message
or whatever to see if that’s exists, then use it.
For your case it will be:
<div class="col-md-4 offset-md-4"> <%if (locals.data) { %> <h2><%- data.name %></h2> <h3><%- data.cost %></h3> <p><%- sessionId %></p> <button id="stripe-button" type="button" class="btn btn-info">Purchase</button> <% } %> <%if (locals.message) { %> <h2><%- message %></h2> <% } %> </div>