How to iterate a json array using mustache?

by darrion.kuhn , in category: Javascript , 2 months ago

How to iterate a json array using mustache?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 2 months ago

@darrion.kuhn 

To iterate a JSON array using Mustache, you can use the {{#arrayName}}...{{/arrayName}} syntax. Here's an example:

  1. JSON data:
1
2
3
4
5
6
7
{
  "users": [
    { "name": "Alice", "age": 25 },
    { "name": "Bob", "age": 30 },
    { "name": "Charlie", "age": 28 }
  ]
}


  1. Mustache template:
1
2
3
4
5
<ul>
  {{#users}}
    <li>{{name}} - {{age}}</li>
  {{/users}}
</ul>


  1. JavaScript to render the template:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var data = {
  "users": [
    { "name": "Alice", "age": 25 },
    { "name": "Bob", "age": 30 },
    { "name": "Charlie", "age": 28 }
  ]
};

var template = document.getElementById("template").innerHTML;
var rendered = Mustache.render(template, data);
document.getElementById("output").innerHTML = rendered;


In this example, the {{#users}}...{{/users}} block iterates over the users array in the JSON data and renders each user's name and age in a list item. The rendered HTML will display a list of users with their names and ages.