Backbone.js jasmine.js测试时无法获取要在下划线.js模板中插入的变量
编辑:忘记提醒读者我记得按如下方式设置templateSettings:Backbone.js jasmine.js测试时无法获取要在下划线.js模板中插入的变量,backbone.js,underscore.js,jasmine,Backbone.js,Underscore.js,Jasmine,编辑:忘记提醒读者我记得按如下方式设置templateSettings: _.templateSettings = { interpolate : /\{\{([\s\S]+?)\}\}/g }; 在运行我的Jasmine规范时,我很难用下划线插入变量。给定以下模板、渲染方法和jasmine测试,我能够通过以下方式获得模板以正确插值变量: _.template( boneHeaderInstance.template.html(), { id:boneHeaderInstan
_.templateSettings = {
interpolate : /\{\{([\s\S]+?)\}\}/g
};
在运行我的Jasmine规范时,我很难用下划线插入变量。给定以下模板、渲染方法和jasmine测试,我能够通过以下方式获得模板以正确插值变量:
_.template(
boneHeaderInstance.template.html(),
{ id:boneHeaderInstance.id,
columns:boneHeaderInstance.columns
}
)
虽然这无法插入columns变量:
boneHeader = Backbone.View.extend({
el: $('#boneTableHeader'),
template: $('#boneTableHeaderTemplate'),
initialize: function(){
this.id = 'boneTableHeader';
this.el = $( '#' + this.id );
this.columns = 'blah';
this.template = $( '#' + this.id + 'Template' );
this.render();
return this;
},
render: function(){
var that = this;
var data = {id: that.id, columns: that.columns}
this.el.html( _.template( this.template.html(), data ) );
}
});
模板:
<script type = 'text/template' id = 'boneTableHeaderTemplate'>
<tr id = "{{obj.id}}Row">
{{obj.columns}}
</tr>
</script>
茉莉花试验:
describe('boneHeader', function(){
beforeEach(function(){
boneHeaderInstance = boneTableInstance.header;
});
describe('rendering', function(){
it('should have expected html', function(){
expect(
boneHeaderInstance.el.html().replace(/\s\t\n/ , '', 'g')
).toEqual(
_.template(boneHeaderInstance.template.html(),
{ id:boneHeaderInstance.id,
columns:boneHeaderInstance.columns
}).replace(/\s\t\n/ , '', 'g')
);
});
});
});
茉莉结果:
Expected ' <tr id="boneTableHeaderRow"></tr> ' to equal ' <tr id = "boneTableHeaderRow"> blah </tr> '
预期''等于'blah'
您有各种各样的问题。首先,除非您使用以下内容进行更改:
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
因此,您的模板应如下所示:
<script type = 'text/template' id = 'boneTableHeaderTemplate'>
<tr id = "<%= obj.id %>Row">
<td><%= obj.columns %></td>
</tr>
</script>
因此,您可能希望在构造函数中使用类似的内容:
this.template = _.template($('#' + this.id + 'Template').html());
在您的渲染中:
this.el.html(this.template(data));
您可以使用.template(template\uhtml,context)
一次完成所有操作
第三,您在模板中引用obj.id
和obj.columns
,但您只给它id
和columns
,因此要么从模板中删除obj.
前缀,要么更改数据
:
var data = {
obj: {
id: that.id,
columns: that.columns
}
};
演示:
当然,您必须修改您的测试以解释更正的HTML。谢谢。我想我已经包括了模板设置
。我正在使用它,并将更新我的问题以反映这一点。很抱歉给你带来了困惑。现在看一下剩下的答案。我还在消化剩下的答案。我同意不需要obj
。你知道为什么obj.id
和obj.columns
在这个代码模板(boneHeaderInstance.template.html(),{id:boneHeaderInstance.id,columns:boneHeaderInstance.columns})中工作吗
?如果没有,没什么大不了的,只是想知道。而且,我不认为这是一个问题。考虑到它在Jasmine消息中正确地插入了obj.id
:Expected''等于'blah'
,这意味着将{{{obj.columns}}
直接放在
之后可能是正确的。谢谢@kikuchiyo:您可以使用\uU4.template(html,数据)
一次性编译和执行模板。但是,如果数据中没有obj
,我看不出{{obj.id}}
是如何工作的。事实上,我提供的一个愚蠢的例子是,
标记中没有
标记导致了这一问题。该死,我真傻+1把这个指向你答案的某个地方。
this.el.html(this.template(data));
var data = {
obj: {
id: that.id,
columns: that.columns
}
};