你如何在node.js的ejs中检查未定义的属性? [英] How would you check for undefined property in ejs for node.js?
问题描述
检查ejs模板中未定义属性的最佳方法是什么?
What is the best way to check for an undefined property in an ejs template?
(我正在使用 node.js包由TJ Holowaychuk提供)
(I'm using the node.js package by TJ Holowaychuk)
示例:
var tpl = '<% if (foo) { %>foo defined<% } else { %>foo undefined<% } %>';
console.log(ejs.render(tpl, { locals: { bar: "baz" } }));
我希望这会渲染foo undefined。它确实会抛出 foo undefined 错误。
I'd expect this to render "foo undefined". It does throw an foo undefined error instead.
我知道这不应该是一个问题,因为这是预期的行为。有没有一种简单的方法可以避免这种情况?
I know that this is not supposed to be an issue, since this is expected behavior in the tests. Is there an easy way to avoid this?
我找到的唯一解决方案是使用 hasOwnProperty
方法。
The only solution I found is using the hasOwnProperty
method.
var tpl = '<% if (hasOwnProperty("foo")) { %>foo defined<% } else { %>foo undefined<% } %>';
console.log(ejs.render(tpl, { locals: { bar: "baz"} }));
这不会引发任何错误。
有更好的方法来保持模板清洁吗?或者为什么会抛出这个错误?
Is there a better way to keep the template clean? Or why does it throw this error?
推荐答案
另一种测试属性的方法是通过<$ c间接引用它$ c> locals 对象。使用您的示例:
Another way to test for a property is to reference it indirectly via the locals
object. Using your example:
var tpl = '<% if(locals.foo){ %>foo defined<% }else{ %>foo undefined<% } %>';
console.log(ejs.render(tpl, { locals: { bar: "baz"} }));
这篇关于你如何在node.js的ejs中检查未定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!