How to iterate a json array using mustache?

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

How to iterate a json array using mustache?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 6 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.

Related Threads:

How to iterate an array of objects in mustache?
How to render a json template using mustache?
How to get html from json data using mustache?
How to save json array in mysql using php?
How to create nested array json using php?
How to update the nested array in json using oracle?