[英]TypeError using underscore.js template with _.find
I was writing a small template like this: 我正在写一个像这样的小模板:
var viewHelpers = {
valExists: function (variable) {
var exists = ((typeof variable == "string") && (variable != ""));
console.log('variable exists: ', exists, ' value: ', variable);
return exists;
},
}
var tpl = '<h1>Hello <%- _.find(["a", "b"], _.valExists) %></h1>';
_.extend(data, viewHelpers);
console.log(_.template(tpl, {
data: data,
}));
I'd expect the template to return '<h1>Hello a</h1>'. 我希望模板返回'<h1> Hello a </ h1>'。
Instead, Firefox display this error: 而是,Firefox显示此错误:
TypeError: t is undefined
What's wrong? 怎么了?
I understand it incorrectly. 我理解不正确。 And I now found my solution.
现在我找到了解决方案。
The problem above occurs when the function is not found in _
object. 当在
_
对象中找不到函数时,会出现上述问题。 And viewHelpers are not meant to be bind to the _
object at all. 而且,viewHelpers根本不打算绑定到
_
对象。 They should just be part of the data providing to template. 它们应该只是提供给模板的数据的一部分。
My code should looks something like this: 我的代码应如下所示:
var tpl = '<h1>Hello <%- _.find(["a", "b"], valExists) %></h1>';
var datalist = {
data: data,
valExists: function (variable) {
var exists = ((typeof variable == "string") && (variable != ""));
console.log('variable exists: ', exists, ' value: ', variable);
return exists;
},
printExists: function (variables) {
return _.find(variables, valExists);
}
}
console.log(_.template(tpl, datalist));
These viewHelpers are actually living in the same namespace as other variables in datalist. 这些viewHelper实际上与数据列表中的其他变量位于同一命名空间中。
To make it looks better, I could separate the definition of viewHelper from the datalist: 为了使它看起来更好,我可以将viewHelper的定义与数据列表分开:
var tpl = '<h1>Hello <%- _.find(["a", "b"], valExists) %></h1>';
var viewHelpers = {
valExists: function (variable) {
var exists = ((typeof variable == "string") && (variable != ""));
console.log('variable exists: ', exists, ' value: ', variable);
return exists;
},
printExists: function (variables) {
return _.find(variables, valExists);
}
}
var datalist = {
data: data,
}
// add the viewHelpers definition to datalist
_.extend(datalist, viewHelpers);
//
console.log(_.template(tpl, datalist));
They are practically the same. 它们实际上是相同的。
My error occurs when my viewHelpers do not exists in the data provided to template. 当提供给模板的数据中不存在viewHelpers时,会发生我的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.