How to render nested data elements using mustache.js?

Member

by darion , in category: Javascript , 21 days ago

How to render nested data elements using mustache.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 20 days ago

@darion 

To render nested data elements using Mustache.js, you can use the dot notation to access nested properties in your data object. Here's an example:


Data object:

1
2
3
4
5
6
7
8
var data = {
  name: "Alice",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown"
  }
};


Template:

1
2
3
4
5
<script id="template" type="text/template">
  <h1>{{name}}</h1>
  <p>Age: {{age}}</p>
  <p>Address: {{address.street}}, {{address.city}}</p>
</script>


Rendering code:

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


Output:

1
2
3
Alice
Age: 30
Address: 123 Main St, Anytown


In this example, the dot notation is used to access the nested address property in the data object within the Mustache template. The rendered template will display the nested data elements correctly.