How to iterate an array of objects in mustache?

by darrion.kuhn , in category: Javascript , 18 days ago

How to iterate an array of objects in mustache?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 17 days ago

@darrion.kuhn 

In Mustache, you can iterate over an array of objects by using the {{#each}} tag. Here's an example of how you can iterate over an array of objects in Mustache:

1
2
3
4
5
<ul>
{{#each users}}
  <li>Name: {{name}}, Age: {{age}}</li>
{{/each}}
</ul>


In this example, users is an array of objects where each object contains name and age properties. The {{#each}} tag will iterate over each object in the users array and render the name and age properties for each object in the list item.


Make sure to pass the array of objects as a parameter to your Mustache template when rendering it, like this:

1
2
3
4
5
6
7
8
9
const users = [
  { name: 'John Doe', age: 25 },
  { name: 'Jane Smith', age: 30 }
];

const template = '{{#each users}}<li>Name: {{name}}, Age: {{age}}</li>{{/each}}';
const rendered = Mustache.render(template, { users: users });

document.body.innerHTML = rendered;


This will render a list with the names and ages of each user in the users array.