How can I use a template that is located in a separate file with mustache JS?
javascript, jquery, mustache
Solution
Here's a 2018 version using fetch to retrieve both the data and the template in parallel:
// Get external data with fetch
const data = fetch('data.json').then(response => response.json());
// Get external template with fetch
const template = fetch('template.mst').then(response => response.text());
// wait for all the data to be received
Promise.all([data,template])
.then(response => {
resolvedData = response[0];
resolvedTemplate = response[1];
// Cache the template for future uses
Mustache.parse(resolvedTemplate);
var output = Mustache.render(resolvedTemplate, resolvedData);
// Write out the rendered template
return document.getElementById('target').innerHTML = output;
}).catch(error => console.log('Unable to get all template data: ', error.message));
Problem
Okay so I want to separate my html and javascript for my project. I want to define a template in a file called template.htm and then use javascript/jQuery to get the file and add the JSON data etc to it then to render/compile it. Script: ``` (function(){ //this is our JSON (data) var data = { "cities": [ {"name": "London"}, {"name": "Paris"}, {"name": "Munich"} ] }, //get a reference to our HTML template src = $.get('../template.html'); template = src.filter("#test").html() //tell Mustache.js to iterate through the JSON and insert the data into the HTML template output = Mustache.render(template, data); //append the HTML template to the DOM $('#container').append(output); })(); ```