判断ejs中是否有variables
这是我的应用程序:
index.js
function index(req, res) { res.render('admin/index'); } module.exports = index;
index.ejs
<% if(data) { %> <div class="alert alert-danger" role="alert">login fail</div> <% } %>
我得到一个错误说:
数据没有定义
我想检查variables是否存在,如果是,则显示对话框。 我该怎么办?
要么重写检查如下:
<% if (typeof data !== 'undefined') { %>
…或者检查locals
(局部variables对象)的属性:
<% if (locals.data) { %>
说明:当EJS将模板编译到函数中时,它不会根据提供的options
填充其variables的堆栈。 相反,它with
语句来包装这个函数:
with (locals || {}) { (function() { // ... here goes the template content })(); }
现在,数据对象( render
第二个参数)作为locals
variables传递到模板函数中,对这个对象进行所有的检查。 重点是,如果访问somevar
从未在本地模板范围(由var
语句)定义,并且不在locals
对象中存在,它会导致ReferenceError: somevar is not defined
错误。
(可以使用_with
来禁用,将_with
选项设置为false
,但是默认情况下它只是未定义的)