mustache.js

January 18, 2018

Grab a recent copy of mustache.js:

<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.js"></script>

Write a Mustache template within a script element:

<script id="template" type="x-tmpl-mustache">
  <table>
    <tr>
      <td align="right"><b>Name:</b></td>
      <td>{{ name }}</td>
    </tr>
    <tr>
      <td align="right"><b>Handle:</b></td>
      <td>{{ nick }}</td>
    </tr>
    <tr>
      <th>Email:</th>
      <td><a href="{{ mbox }}">{{ mbox }}</a></td>
    </tr>
    <tr>
      <th>Website:</th>
      <td><a href="{{ homepage }}">{{ homepage }}</a></td>
    </tr>
    <tr>
      <th>Depiction:</th>
      <td><img class="thumbnail" src="{{ depiction }}"></img></td>
    </tr>
  </table>
</script>

Add an element to hold the rendered view:

<div id="target"></div>

Grab the model from a JSON API and render the view from the template:

<script type="text/javascript">
  function render(modelUrl, templateId, targetId) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        var model = JSON.parse(xhr.responseText);
        var template = document.getElementById(templateId).innerHTML;
        var view = Mustache.render(template, model);
        document.getElementById(targetId).innerHTML = view;
      }
    }
    xhr.open('GET', modelUrl, true);
    xhr.send();
  }
</script>

Make it so:

<script type="text/javascript">
  render('/james.json', 'template', 'target');
</script>

Demo