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 cellspacing="5">
    <tr>
      <td align="right"><b>Name:</b></td>
      <td>{{ name }}</td>
    </tr>
    <tr>
      <td align="right"><b>Nick:</b></td>
      <td>{{ nick }}</td>
    </tr>
    <tr>
      <td align="right"><b>Homepage:</b></td>
      <td><a href="{{ homepage }}">{{ homepage }}</a></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>
<script type="text/javascript">
  render('/james.json', 'template', 'target');
</script>

Demo