Forewarning, this is a hack and an ugly one too. Without getting into the backstory, the idea was to see if it is possible to render YAML data to HTML using a Mustache template, all locally (i.e. no server, just a single local HTML file). Turns out it is possible... sort of.
Before getting to the code, a few notes:
- This probably shouldn't be used for anything ever (although it was a fun experiment).
- To read the local files,
iframe
elements are used; I feel like there is probably a library or some more elegant way to do this but didn't take the time to look. - This example only worked on Firefox 32 for me.
- Chrome 37 has security features that prevents the local files from being read (supposedly they can be disabled but I didn't have any luck).
- Internet Explorer 8 complained about security as well and rendered nothing.
The results of this experiment are three files:
data.yaml
- Contains the information that will be rendered.template.txt
- Contains the Mustache template used to render the YAML data.page.html
- Handles rendering the output to the browser.
The contents of the files are the following:
data.yaml
items:
- date: "2014-09-15"
note: "foo"
- date: "2014-09-20"
note: "bar"
- date: "2014-09-25"
note: "baz"
template.txt
<h1>Interesting Stuff</h1>
{{#items}}
{{date}}
</br>
{{note}}
<p>
{{/items}}
page.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/nodeca/js-yaml/master/dist/js-yaml.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/janl/mustache.js/master/mustache.js"></script>
</head>
<body>
<iframe id='yloader' src='data.yaml'></iframe>
<iframe id='tloader' src='template.txt'></iframe>
<div id="container"></div>
<script>
window.onload = function(){
$('#yloader').hide(); $('#tloader').hide(); /* Hide loader iframes. */
var yaml = $('#yloader').contents().find('pre').text();
var template = $('#tloader').contents().find('pre').text();
var data = jsyaml.load(yaml);
var output = Mustache.render(template, data);
$('#container').append(output);
}
</script>
</body>
</html>