我有一个动物阵列:
var animals = [new animal("giraffe", false, 4), new animal("zebra", false, 8), new animal("lion", false, 10), new animal("dog", true, 4), new animal("cat", true, 2)];
如何将其传递给车把并进行迭代?基本上,我想展示所有动物,每只动物都展示它的所有特性。
由于 胡志明
答案 0 :(得分:1)
我自己想出来,为了做我想做的事。我需要这样做:
Server.js:
var animals = [new animal("giraffe", false, 4), new animal("zebra", false, 8), new animal("lion", false, 10), new animal("dog", true, 4), new animal("cat", true, 2)];
// Routes:
app.get("/allpets",function(req,res){
res.render("allpets", {pets: animals});
};
app.get("/pets/:id",function(req,res){
var type = req.params.id;
var index = -1
for(var i = 0; i < animals.length; i++){
if(animals[i].type === type){
index = i;
break;
}
res.render("animal", animals[index]);
});
然后,我们需要创建2个车把视图。一个叫做allpets.hbs,另一个叫做animal.hbs
allpets.hbs:
<ul>
{{#each pets}}
<li>
<p>Type: {{type}}</p>
<p>Pet: {{pet}}</p>
<p>Fierceness: {{fierceness}}</p>
</li>
{{/each}}
</ul>
============================================================
animal.hbs:
<ul>
<p>Type: {{type}}</p>
<p>Pet: {{pet}}</p>
<p>Fierceness: {{fierceness}}</p>
</ul>