-1

I have an animal array:

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)];

How do I pass it to the handlebar and iterate it ? Basically, I want to display all animals, with each of animal, display all of its properties.

Thanks Minh

Hoang Minh
  • 1,066
  • 2
  • 21
  • 40

1 Answers1

1

I have figured it out myself, in order to do what I want. I need to do:

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]);
});

Then, we will need to create 2 handlebar views. One is called allpets.hbs, the other one is called 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>
Hoang Minh
  • 1,066
  • 2
  • 21
  • 40