[英]Throw/catch error when a variable is undefined using underscore
我想知道当模板中未定义变量时是否有解决方案引发错误?
例:
function hello() {
var data = { foo: 'hello' };
//data.bar is undefined, data.bar will be replaced by an empty string by underscore
var render = _.template('<p><%= data.foo %><%= data.bar %></p>', {data: data});
//Rendering okay? true|false
//if (render...)
}
如果在调用_.template函数后未定义变量data.boo,我想抛出一个错误。 您是否有可能做类似的事情? 我检查了文档,但不幸的是没有找到任何有趣的东西...
谢谢
无论是好是坏,Underscore都会为您提供顶级属性:
var data = { foo: 'hello' };
var rendered = _.template('<p><%= foo %><%= bar %></p>', data);
// throws ReferenceError: bar is not defined
这是因为Underscore模板with
使用,因此顶级属性被视为变量。 如果要在子对象属性上出现错误,则需要自己添加,也可以使用with
:
var data = { foo: 'hello' };
// throw
var rendered = _.template('<% with (data) { %><p><%= foo %><%= bar %></p><% } %>',
{ data: data });
或者您可以使用显式throw
,例如
<% if (data.bar === undefined) throw "No bar!"; %>
在模板的开头。 但是,实际上,您为什么要这样做呢? 如果知道要检查的内容,最好进行显式的预渲染检查并在那里进行处理,并避免在控制流中使用错误:
var rendered;
if (data.foo !== undefined) rendered = _.template("...", { data: data });
else {
// do something else
}
就像@mechanicalfish所说的那样,您尝试做的事情似乎不正确。 您应该在模板之外验证数据。 无论哪种情况,这都是您要的:
function hello() {
var data = { foo: 'hello' };
//data.bar is undefined, data.bar will be replaced by an empty string by underscore
var render = _.template('<p><%= data.foo %><% ' +
' if (!data.bar) { ' +
' throw "data.bar is undefined" ' +
' } else { ' +
' print(data.bar) ' +
' } ' +
' %></p>', {data: data});
//Rendering okay? true|false
//if (render...)
}
JavaScript具有try / catch支持。
function hello() {
var data = { foo: 'hello' };
try {
//data.bar is undefined, data.bar will be replaced by an empty string by underscore
var render = _.template('<p><%= data.foo %><%= data.bar %></p>', {data: data});
} catch (e){
throw "data.bar is undefined";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.