How to Load Mustache.js Templates From an External File with jQuery

Recently, I’ve been hearing a lot about all the different JavaScript templating libraries out there. Well, I decided to sit down with with Mustache.js and tinker around with it. One of the first stumbling blocks I ran into was figuring out how to load a template that’s stored in an external file. After doing some digging into a bunch of different blog posts online, I’ve figured out that it boils down to just a couple of basic steps:

  1. Dump the template code into an HTML file
  2. Load the template file into your code using jQuery’s $.get method, grab the desired HTML, and render it

1. Dump the code into an HTML file

When you declare a mustache template directly into your code, it’s usually just a simple JavaScript string stored in a variable:

$(document).on('pageinit', function() {
    $.getJSON('assets/data/channels.json', {}, function(channelData, textStatus, jqXHr) {
        var channelList = $('#channels'),
            template;
        // The template var is just a string
        template = '<li><img src = "http://placehold.it/80x80"><span></span></li>';
        channelList.append(Mustache.to_html(template, channelData))
        channelList.listview("refresh");
    });
});

Here we’re just rending a bunch of music channels into a jQuery mobile list view. And all of this works fine, but the template is not very easy to maintain. Now we’ll move in into an external HTML file:

<!--
[channelList.mustache.html]
This is the template for items in the channel list for when the app first loads
-->
<script id="channelTpl" type="text/html">

<li>
    <img src = "http://placehold.it/80x80">
    <span></span>
</li>

</script>

Side Note: The .mustache in the file name doesn’t do anything. I just put it there in case I wanted to use the same code with a different templating engine.

You’ll notice that everything is pretty much the same from our first example except that we’ve wrapped our code in `` tags and given that tag an ID of channelTpl. This will come in handy later when we load in the template via the $.get method.

2. Load the template file into your code using jQuery’s $.get method, grab the desired HTML, and render it

Okay, now that we’ve got our external file set up, we need to modify our code to pull in the file:

$(document).on('pageinit', function() {
    $.getJSON('assets/data/channels.json', {}, function(channelData, textStatus, jqXHr) {
        var channelList = $('#channels');

        $.get('assets/templates/channelList.mustache.html', function(template, textStatus, jqXhr) {
            channelList.append(Mustache.render($(template).filter('#channelTpl').html(), channelData))
            channelList.listview("refresh");
        });
    });
});

As you can see, we’re pulling in the template file in using $.get. The callback for that method receives a variable called template which contains all the code stored in the file. However, Mustache doesn’t like stuff like `` tags in its templates so we use jQuery to filter down through the template to where we can return just the HTML we want to render. Here, we’re asking for everything inside the script tags. Also notice how in the previous example we called Mustache.to_html where this time we’re calling Mustache.render. This is because we are no longer passing in a raw JavaScript string value so we don’t need to convert it to HTML before rendering it.

Final Thoughts

Well, I hope this helps someone out. Please keep in mind that this is my first attempt at really doing anything with Mustache.js and JavaScript templates in general. If I’ve done something wrong or you know of a better way to accomplish what we’ve talked about here, please let me know in the comments below.