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.
JavaScript
x
8
1
button.addEventListener("click",function()
2
{
3
//here i face an error when sessionID is not available
4
stripe.redirectToCheckout({
5
sessionId:'<%= sessionId %>'
6
})
7
})
8
here is the code in which I use conditions inside the EJS.
JavaScript
1
12
12
1
<div class="col-md-4 offset-md-4">
2
<%if (data) { %>
3
<h2><%- data.name %></h2>
4
<h3><%- data.cost %></h3>
5
<p><%- sessionId %></p>
6
<button id="stripe-button" type="button" class="btn btn-info">Purchase</button>
7
<% } %>
8
<%if (message) { %>
9
<h2><%- message %></h2>
10
<% } %>
11
</div>
12
It also shows an error when it do not receive any message variable.
Error which I received is:
JavaScript
1
2
1
message is not defined. sessionID is not defined.
2
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:
JavaScript
1
12
12
1
<div class="col-md-4 offset-md-4">
2
<%if (locals.data) { %>
3
<h2><%- data.name %></h2>
4
<h3><%- data.cost %></h3>
5
<p><%- sessionId %></p>
6
<button id="stripe-button" type="button" class="btn btn-info">Purchase</button>
7
<% } %>
8
<%if (locals.message) { %>
9
<h2><%- message %></h2>
10
<% } %>
11
</div>
12