Search code examples
node.jsexpressejsbackendvisual-web-developer

How to use template in the loop statement in EJS?


I am making a Express based Node JS project which prints out a particular array of elements among a given set of Arrays by using EJS loop.

app.get("/:animal", function(req,res) {
var animal = req.params.animal;
var cats = [
    { name : "Mittens", age : 7},
    { name : "Kitty", age : 11},
    { name : "Smoogy", age : 3}
];
var dogs = [
    { name : "Rusty", age : 14},
    { name : "Matt" , agee : 7},
    { name : "Holly" , age : 9}
]

res.render("abc.ejs", {animal : animal, cats : cats, dogs : dogs});

These are my 2 arrays, and I have to print out any one of them based on what is the value of the animal parameter. I want to do this without writing the forEach loop separately for cats and dogs in the EJS file, rather want to print on the basis of the value of animal parameter. How to do so? I tried using nested <% %> tags but didn't work


Solution

  • I would recommend to use objects in javascript to handle your case as mentioned below

    In your route file,no need of extension ejs

    router.get('/:animal', function(req, res) {
    	var animal = req.params.animal;
    	var cats = [ { name: 'Mittens', age: 7 }, { name: 'Kitty', age: 11 }, { name: 'Smoogy', age: 3 } ];
    	var dogs = [ { name: 'Rusty', age: 14 }, { name: 'Matt', agee: 7 }, { name: 'Holly', age: 9 } ];
    
    	var map = { cats: cats, dogs: dogs };
    
    	res.render('abc', { animals: map[animal] });
    });

    Ejs view file as below:

    <table>
        <tbody>
    <% animals.forEach(function(animal) { %>
        <tr>
          <td><%= animal.name %></td>
          <td><%= animal.age %></td> 
        </tr>
      <% }); %> 
    </tbody>
    </table>

    Then hit the endpoints, can change based on your port and host http://localhost:3000/dogs

    http://localhost:3000/cats