如何检查 EJS 变量是否存在?
How can I check if an EJS variable exists?
我在 Node.js 应用程序中使用了 EJS 布局。目前,当 EJS 文件中所需的数据不可用时,我遇到了一个问题,它只会生成一个错误。我想要的是在 javascript.
中使用 EJS 变量之前添加一个条件
这是我的代码,我在脚本标签中使用了 EJS 变量。
button.addEventListener("click",function()
{
//here i face an error when sessionID is not available
stripe.redirectToCheckout({
sessionId:'<%= sessionId %>'
})
})
这是我在 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>
当它没有收到任何消息变量时也显示错误。
我收到的错误是:
message is not defined. sessionID is not defined.
您的 if 检查不正确。您可以检查 locals.message
或其他任何内容以查看它是否存在,然后使用它。
你的情况是:
<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>
我在 Node.js 应用程序中使用了 EJS 布局。目前,当 EJS 文件中所需的数据不可用时,我遇到了一个问题,它只会生成一个错误。我想要的是在 javascript.
中使用 EJS 变量之前添加一个条件这是我的代码,我在脚本标签中使用了 EJS 变量。
button.addEventListener("click",function()
{
//here i face an error when sessionID is not available
stripe.redirectToCheckout({
sessionId:'<%= sessionId %>'
})
})
这是我在 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>
当它没有收到任何消息变量时也显示错误。
我收到的错误是:
message is not defined. sessionID is not defined.
您的 if 检查不正确。您可以检查 locals.message
或其他任何内容以查看它是否存在,然后使用它。
你的情况是:
<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>