How to render a plain array with mustache.js?

by ryan.murray , in category: Javascript , 6 months ago

How to render a plain array with mustache.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 6 months ago

@ryan.murray 

To render a plain array with Mustache.js, you can use a template that loops through each item in the array and renders it. Here's an example:

  1. Define your array:
1
2
3
const data = {
  items: ['apple', 'banana', 'orange']
};


  1. Create a Mustache template that iterates over the items array:
1
2
3
4
5
6
7
<script id="template" type="text/html">
  <ul>
    {{#items}}
      <li>{{.}}</li>
    {{/items}}
  </ul>
</script>


  1. Compile the template and render it with your data:
1
2
3
const template = document.getElementById('template').innerHTML;
const rendered = Mustache.render(template, data);
document.getElementById('output').innerHTML = rendered;


  1. Add an element in your HTML where the rendered output will be displayed:
1
<div id="output"></div>


When you run this code, it will iterate over the items array and render each item as a list item in an unordered list. The final output will look like this:

  • apple
  • banana
  • orange


This is a simple example of how to render a plain array with Mustache.js. You can customize the template and data to fit your specific needs.

Related Threads:

How to render nested data elements using mustache.js?
How to render data in 2d tables via mustache.js?
How to render one element of an array in mustache?
How to render object data in d3.js?
How to use @apply from tailwind in plain css?
How to get plain text files in doxygen documentation?