gpt4 book ai didi

javascript - EJS 无法渲染模板

转载 作者:行者123 更新时间:2023-12-03 08:17:21 25 4
gpt4 key购买 nike

我正在尝试渲染一个包含以下代码块的模板:

<% if(type === 'Not Within Specifications'){ %>
<% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% } %>
<% if(Width !== undefined) { %><h5>Width: <%= Width %> </h5> <% } %>
<% if(thickness !== undefined) { %><h5>Thickness: <%= thickness %> </h5> <% } %>
<% } %>

但是,当模板尝试渲染时,如果上述变量之一实际上未定义,它会抛出变量“未定义”的错误。

if 语句捕获 undefined variable 的目的是为了消除此错误的发生,但是即使我检查变量是否未定义,该错误似乎仍然会抛出。有谁知道为什么会这样?非常感谢!

最佳答案

您需要使用typeof:

<% if(type === 'Not Within Specifications'){ %>
<% if(typeof Length !== 'undefined') { %><h5>Length: <%= Length %> </h5> <% } %>
<% if(typeof Width !== 'undefined') { %><h5>Width: <%= Width %> </h5> <% } %>
<% if(typeof thickness !== 'undefined') { %><h5>Thickness: <%= thickness %> </h5> <% } %>
<% } %>

另外,请参阅此相关问题:How would you check for undefined property in ejs for node.js?

关于javascript - EJS 无法渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com