How to fetch json in mustache template?

Member

by domenico , in category: Javascript , 2 months ago

How to fetch json in mustache template?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 2 months ago

@domenico 

Mustache is a logic-less template language, so you cannot directly fetch JSON data within a Mustache template. However, you can render JSON data in your template by passing it to the template engine (like Handlebars) before rendering the template.


Here's an example using JavaScript with Handlebars:

  1. Install Handlebars using npm:
1
npm install handlebars


  1. Create a template file (template.hbs) with the following content:
1
2
3
4
5
<ul>
  {{#each items}}
    <li>{{name}}</li>
  {{/each}}
</ul>


  1. Create a JavaScript file (index.js) to fetch JSON data and render it in the template:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const Handlebars = require('handlebars');
const fs = require('fs');

// Load the template
const template = fs.readFileSync('template.hbs', 'utf8');

// Load the JSON data
const data = require('./data.json');

// Compile the template
const compiledTemplate = Handlebars.compile(template);

// Render the template with the JSON data
const renderedTemplate = compiledTemplate(data);

console.log(renderedTemplate);


  1. Create a JSON file (data.json) with the following content:
1
2
3
4
5
6
{
  "items": [
    { "name": "Item 1" },
    { "name": "Item 2" }
  ]
}


  1. Run the script using Node.js:
1
node index.js


This will fetch the JSON data from the data.json file and render it in the template, outputting an HTML list with the item names.


Remember that you need to handle data fetching and passing before rendering the template using a template engine like Handlebars.