我想创建一个模板,并希望在其中包含四个html div元素。现在在我的视图文件中,我想将不同的数据填充到这四个模板元素中。以下是我打算实现的目标。
Html文件:
<script id = "four-child-template">
<div id = "one>
<div id = "two">
<div id = "three">
<div id = "four">
</script>
查看文件:
var widgetdata = new widgetdata.chart({});
var myChartView4 = Backbone.View.extend({
render: function()
{
// I want to put four different data coming from model to the template div elements
// need help here. how to inject different values coming from models to corresponding div tags.
$(this.el).html(this.model.attributes.incThisYear[this.model.attributes.incThisYear.length-1]);
},
initialize: function()
{
this.model.on('change', this.render, this); // registering on change of model
}
});
new myChartView4({
el: '#four-child-template',
model: widgetdata
});
解决问题的尝试1:
<body>
<div id="divForRender"></div>
</body>
<script id = "four-child-template">
<div id="one"><%= j.attr1 %></div>
</script>
// WORKING for one ttop bar
var widgetdata = new chartmodel.chart({});
var myChartView4 = Backbone.View.extend({
template: _.template($('#four-child-template').html()),
render: function()
{
var j = {}; // can use model.toJSON() but if you only want specific attributes then just assign as needed
j.attr1 = "hello" ;
$(this.el).html(this.template(j));
},
initialize: function()
{
this.model.on('change', this.render, this); // registering on change of model
}
});
var t = new myChartView4({
el: '#divForRender',
model: widgetdata
});
t.render();
错误:VM6554:6未捕获的ReferenceError:未定义j
答案 0 :(得分:2)
渲染视图时,它会将html注入divForRender。
<body>
<div id="divForRender"></div>
</body>
设置模板,然后假定可以预期的JSON数据类型。
<script id = "four-child-template">
<div id="one"><%= attr1 %></div>
<div id="two"><%= attr2 %></div>
<div id="three"><%= attr3 %></div>
<div id="four"><%= attr4 %></div>
</script>
var widgetdata = new widgetdata.chart({});
查看设置
var myChartView4 = Backbone.View.extend({
/* Let the template in the view point to the above defined template id. */
template: _.template($('#four-child-template').html()),
render: function()
{
/* Grab the relevant parts of the model and create object to pass to template. */
var j = {}; // can use model.toJSON() but if you only want specific attributes then just assign as needed
j.attr1 = this.model.get('myAttribute1');
j.attr2 = this.model.get('myAttribute2');
j.attr3 = this.model.get('myAttribute3');
j.attr4 = this.model.get('myAttribute4');
$(this.el).html(this.template(j));
},
initialize: function()
{
this.model.on('change', this.render, this); // registering on change of model
}
});
var cv4 = new myChartView4({
el: '#divForRender',
model: widgetdata
});
cv4.render();