模板不支持主干和把手
问题描述:
在这里我有问题要呈现我的模板与把手和骨干。 我不知道为什么我的每个块都不起作用。 我重写我的模板几次和我的JSON,但它从来没有工作。 如果有人有一个想法在我的错在这里:)模板不支持主干和把手
这里我的index.html:
<body>
<div id="page">
</div>
<script type="text/x-handlebars-template" id="template">
<h4> test template </h4>
{{#each rappers}}
<p>{{rappers.blazz}} !!!!!!</p>
{{/each}}
</script>
</body>
我得到了这样的结果:
test template
!!!!!!
!!!!!!
!!!!!!
而不是{{blazz}}值..
这里我JS:
var Rapper = Backbone.Model.extend({
// defaults : {
// blazz: ""
// },
initialize: function() {
console.log("Création d'un nouveau rapper");
}
})
var Rappers = Backbone.Collection.extend({
// defaults : {
// blazz: "pas de blazz"
// },
model : Rapper,
url : './js/data.json'
})
var RapperList = Backbone.View.extend({
el:'#page',
render: function(){
var that = this;
var rappers = new Rappers();
rappers.fetch({
success: function(rappers){
var source = $("#template").html();
var template = Handlebars.compile(source);
that.$el.html(template({rappers : rappers.toJSON()}));
}
})
}
});
var Router = Backbone.Router.extend({
routes:{
'' : 'home'
}
});
var rapperList = new RapperList();
var router = new Router();
router.on('route:home',function(){
rapperList.render();
})
Backbone.history.start();
我的JSON:
[
{"rapper" :
[
{"blazz" : "person1"},
{"nom" : "paul"},
]
},
{"rapper" :
[
{"blazz" : "person2"},
{"nom" : "mike"},
]
},
{"rapper" :
[
{"blazz" : "person3"},
{"nom" : "jean"},
]
}
]
答
这里我的解决办法:
我稍微改变了代码的形状。 (并添加了几个项目)。
所以这里的新JSON:
[
{
"blazz" : "blazz1",
"prenom" : "prenom1",
"age" : 20,
"album" :
[
{
"nom" : "album1",
"vente" : 1000}
,
{
"nom" : "album2",
"vente" : 10068
}
]
},
{
"blazz" : "blazz2",
"prenom" : "prenom2",
"age" : 15,
"album" :
[
{
"nom" : "album1",
"vente" : 1000}
,
{
"nom" : "album2",
"vente" : 108798
}
]
},
{
"blazz" : "blazz3",
"prenom" : "prenom3",
"age" : 35,
"album" :
[
{
"nom" : "album1",
"vente" : 6546
}
,
{
"nom" : "album2",
"vente" : 4816
}
]
}
]
,这里的新模板:
{{#each rappers}}
<p>blazz: {{blazz}} prenom: {{prenom}} nom: {{nom}}</p>
<ul>
{{#each this.album}}
<li>nom: {{nom}}</li>
{{/each}}
</ul>
{{/each}}
这里的区别是: 前:
{"object" :
[
{"foo" : "content"},
{"foo" : "content"}
]
}
并经过
{"object" :
[
{"foo" : "content",
"foo" : "content"}
]
}
答
你可以试试这个:
<body>
<div id="page">
</div>
<script type="text/x-handlebars-template" id="template">
<h4> test template </h4>
{{#each rappers}}
<p>{{blazz}} !!!!!!</p>
{{/each}}
</script>
</body>
通过使用直接{{} blazz而不是{{} rappers.blazz
你可以重新排列你的数据吗?像这样的单个入口对象不能很好地与Handlebars相匹配,单个'{blaze:'person3',nom:'jean'}'对象将更容易处理。 –
不幸的是我不得不保留格式化数据 – user3264208