EJS无法呈现模板

EJS failing to render template

本文关键字:EJS      更新时间:2023-09-26

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

<% 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语句捕获未定义变量的目的是避免发生此错误,但是,即使我检查变量是否未定义,错误似乎仍在抛出。有人知道为什么会这样吗?非常感谢!

您需要使用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> <% } %>
 <% } %>

另外,请参阅这个相关问题:如何检查node.js的ejs中的未定义属性?

相关文章:
  • 没有找到相关文章