JavaScript templates

Separating our HTML from our JavaScript into small reusable pieces.


Just like not having CSS in our JavaScript, we don’t want to cross the streams with our HTML—so templates allow us to keep our HTML in the HTML file and not have it in our JavaScript code.


There are lots of different JavaScript template engines; one really popular one is Mustache.

In our HTML we would provide the template, like this:

<script id="template" type="x-tmpl-mustache">
  <h1>Hello !</h1>

Using JavaScript, we can read the template and put some information into it:

// Mustache uses objects to represent the data for the template
var data = {
  name: 'Thomas'

// We grab the template from our HTML and get it ready
var template = $('#template').html();

// Then we take the template and render it with our data
var rendered = Mustache.render(template, data);

// We could then insert the rendered HTML into our page


Video list

  1. JavaScript DOM: Templates
  2. JavaScript DOM: Templates & forms
  3. JavaScript DOM: Event delegation