Reputation: 625
There is a file for the mustache folder called mustache.js-master in github. It has a number of different files including mustache.min.js, mustache.js, bin folder, hooks folder, spec folder, test, etc. How do I install mustache, do i just download the file and include mustache.js in my code, or is there a way to install the file?
I just included the mustache.js file in my project folder and wrote the tag in my code. Here is some code that I wrote to see if it works, the output from both the console.log and the document.write are empty. Is there anything wrong with my code or was I supposed to install mustache in a different way?
<script type ="text/javascript" src ="jquery.js"></script>
<script type="text/javascript" src = "mustache.js"></script>
<script>
var template;
var data;
template = '<div><h2>{{Title}}</h2><p>{{Course}}</p><p>{{Category}}</p></div>';
data = '[{"Title":"Algorithms","Course":"CSI241","Category":"science"},{"Title":"Fluid dynamics","Course":"PHY345","Category":"science"}]';
var html = Mustache.to_html(template,data);
console.log(html);
document.write(html);
</script>
Upvotes: 3
Views: 3717
Reputation: 113507
Download the mustache.min.js
file, since you're not gonna edit that code.
But you have another problem: the to_html
expects a template and an object. Your data
variable is a string containing some JSON. You have to parse it as JSON (if you're getting it as string) or passing it directly as object (if you already know what you have there).
I also wrapped your data
array into an object like this { data: data }
to be able to repeat the snippets.
Here is an example:
var template = '{{#data}}<div><h2>{{Title}}</h2><p>{{Course}}</p><p>{{Category}}</p></div>{{/data}}';
var data = JSON.parse('[{"Title":"Algorithms","Course":"CSI241","Category":"science"},{"Title":"Fluid dynamics","Course":"PHY345","Category":"science"}]')
var html = Mustache.to_html(template, { data: data });
document.body.innerHTML = html;
<script src="https://cdn.rawgit.com/janl/mustache.js/master/mustache.min.js"></script>
Upvotes: 5