Using mustache templates with Django.

There are various reasons why you might want to use client side templates in a Django app. For example, you might want to make your initial page load faster, return some of your data in json format and postpone some template rendering until the user needs it.

Let's see how we can easily include mustache templates in Django. This page explains the mustache syntax quite well.

The most optimized way to include a client side template in your code would be to compile it on deployment and include the compiled JavaScript file as part of your static files. However, that seemed like too much work and I wanted something that I can implement faster.

If you're not shipping compiled JavaScript, then your other option would be to have the template text somewhere and compile it client side. I have one main requirement though - I don't want my template code to be in a string which editors will display without HTML syntax highlighting.

So, working with these constraints, let's see what we can come up with.

First, let's say our template code is in person.html and it looks like this:

<div>
  {{#person}}
    The user's name is {{name}}.
  {{/person}}
  {{^person}}
    There's no user defined.
  {{/person}}
</div>

Now, we can include this template in the html page returned by our initial page load, like this:

<script>
  var person_template_text = `{% include "myapp/templates/person.html" %}`
</script>

In this case, person_template_text is a template literal. Template literals are JavaScript strings that can span multiple lines.

Now, we just need to compile the template so that it's ready to be rendered. We'll use hogan.js, since it's advertised as faster and smaller than mustache and it fully supports mustache syntax. Let's say we're also using jQuery. We can do something along these lines:

function App() {
  this.person_template = Hogan.compile(person_template_text);
}

App.prototype.renderPerson = function(personDict) {
  return this.person_template.render(personDict);
}

var app;

$(document).ready(function() {
  app = new App();
});

And that's it. There are many other ways to do this, which will be more optimized, but this one seems like an easy one to start with.

social