Quick Tip: Using the Mustache Template Library
videos

Quick Tip: Using the Mustache Template Library

Tutorial Details
  • Topic: Mustache Template Library
  • Format: 5 minute screencast
  • Difficulty: Beginner
Download Source Files

Not long ago, I demonstrated how to use the Mustache, which is just as easy to use.



View Screencast

Step 1: Download Mustache

You can get Mustache.js from its GitHub project page; if you’re going to use it in a project, you can download it or git clone it; I’ve just referenced the raw file on GitHub for this quick tip:

 <script src="http://github.com/janl/mustache.js/raw/master/mustache.js"></script>

Now you can use it to render data!


Step 2: Get Your Data

Most likely, you’ll be getting your data from the server in the form of JSON when you’re using Mustache in production. However, it’s just as easy to hard-code an object literal and use that, which is what we’ll do here.

var data = {
    name : "Some Tuts+ Sites",
    sites: ["Nettuts+", "Psdtuts+", "Mobiletuts+"],
    url : function () {
        return function (text, render) {
            text = render(text);
            var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
            return '<a href="' + url + '">' + text + '</a>';
        }
    }
};

Now we’re ready to define the template.


Step 3: Create your Template

Your template is simply string; you can either use a regular old JavaScript string, or you can put the template in a script tag and get it via something like jQuery’s html() method (or, of course, innerHTML). This is probably a better choice if you’re using a complicated template, because you can use line breaks. Just remember to give the script a type of something other than “text/javascript”; otherwise, browsers may try to interpret it, and that will cause errors.

Your template will be mainly HTML; when you want to use a value from your data, reference the key name of the value in the data. To use the name value in the data above, you’d reference it like this:

<h1> {{name}} </h1>

Blocks are an important piece of Mustache: you can use them to get inside arrays and objects, as well as for lambdas (functions). It’s pretty simple to do blocks: just use an opening and closing tag: the opening one starts with a pound (#) and the closing one with a slash(/).

<ul>
    {{#sites}}

        <li> {{.}} </li>

    {{/sites}}
</ul>

When iterating over arrays, the implicit operator ”.” will get you the value. If sites was an object, you’d use it’s keys inside the block.

Using functions is a little more tricky. For the data part, Mustache.js requires a function that returns the function to be used. That function gets passed the text to be rendered (all the text within the mustache function tags) and a function that will render the template tags inside the text. Then, whatever that function returns will be put within the tags. You can see this at work in the urls function in the data above.


Step 4: Render the HTML

It’s really simple to render the HTML:

html = Mustache.to_html(template, data);

Then, you can stick that HTML wherever you want.


The Complete Source

var data, template, html;

data = {
    name : "Some Tuts+ Sites",
    sites: ["Nettuts+", "Psdtuts+", "Mobiletuts+"],
    url : function () {
        return function (text, render) {
            text = render(text);
            var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
            return '' + text + '';
        }
    }
};

template = "

{{name}}

    {{#sites}}
  • {{#url}} {{.}} {{/url}}
  • {{/sites}}
"; html = Mustache.to_html(template, data); document.write(html)

Conclusion

To learn more about Mustache, check out the website. Have fun with it!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • yassir

    very interesting thanks for the tip.
    anyway isn’t there a templating plugin for jquery ?

  • Yosy

    yassir, “I demonstrated how to use the Microsoft’s jQuery template plugin”.

    Thanks for the tip :)
    Very helpfull

  • Dan

    I’m fairly new to this stuff so I don’t see any practical implementations of this script. I’m trying to wrap my head around why this is useful.

    Is this similar to using includes?

    Is it possible to give a few real world situations where this would be practical?

    • Gigamo

      It could be useful for example when you’re receiving a JSON response from the server (think ajax) and want to render something out of that object.

    • http://hosting4developers.com Hosting 4 Developers

      This is useful for when you want to build a page (or part of a page) using JavaScript. If you don’t use a templating system like the one above, you’ll likely end up with a mix of JavaScript and HTML which is hard to read and change. So the reason for using the above system is the same as the reason you use MVC frameworks when working with serverside languages: Separation of code and HTML.

      • http://krike.cmstutorials.org krike

        nice example, I wasn’t really sure myself why this would be usefull :) but now i see how it could be an advantage :)

    • http://www.alvinmilton.com AGDM

      An effort toward separating logic and presentation…

  • http://jonathonmorgan.net Jonathon

    @yassir check out tmpl. It’s an update on John Resig’s micro-templating idea. Here’s the most stable version I’ve found: http://github.com/nje/jquery-tmpl. Check out discussion on jQuery forums for some extra insight into the syntax: http://forum.jquery.com/topic/templating-syntax

    I like because it works really well with jQuery’s ajax methods, so you can keep templates in external files and call them when necessary, ala something you’d do in a server side language.

  • w1sh

    Thanks for the look Andrew. Btw, who got who into Vim?

    But before you guys start grabbing your copies of Mustache.js from all over, you need to know…
    <>

    I would love to see this quickie on PHP though. Regardless I’m going to check it out. Once I figure out the PHP ver, I’ll drop a link.

    • http://andrewburgess.ca Andrew Burgess
      Author

      Thanks! I started using Vim a few months ago, mainly because I didn’t want to pay for a text editor, and I’d heart a lot of great things about Vim. I’ve been loving it!

      • http://hosting4developers.com Hosting 4 Developers

        If your sole reason for using Vim is that it’s free, there are a lot of other great alternatives :) Personally I prefer Komodo Edit.

      • http://andrewburgess.ca Andrew Burgess
        Author

        Well, that may have been my original reason, but now I’m pretty sure sticking with it will make me more productive in the long run :)

      • George

        yeah but netbeans and phpstorm got really good implementations of vim, so we are not stuck with it… I use vim for small projects and bought phpstorm for bigger projects, and use it with ideaVim. Perfect combination… xrefresh, vimperator and youre good to go…

    • w1sh

      I’m friggin’ silly. I went to emphasize “This will not work with JavaScript disabled.” with arrow brackets and it stripped it.

      Anyway, point is, these JS tuts for displaying data seem far-fetched in real world applications.

    • w1sh

      To answer Dan above: I went over the docs and it looks like a really, really simple templating system.

      And to bail on the PHP tut: Mustache really doesn’t look super useful right away. I’m sure it has it’s purposes, but the only advantage it has over regular ol’ PHP is that you can call variables like so:

      {{calling_this_var_is_slightly_smaller}}

      Whereas PHP:

      Of course there are times like when you’re iterating something that Mustache looks exceptionally smaller, but there are already so many things to constantly be studying… it seems like the pro’s of learning something like Mustache would be heavily outweighed by the con’s of time-spent on it. You’d be better served learning a feature-rich templating framework like Smarty – or better yet – just bespoke your own object-oriented templating system as you go and reuse it.

      • w1sh

        pre name=”code” class=”php” didn’t seem to work. And why the hell can’t we “Edit” our comments???

      • http://brianegan.com Brian Egan

        Hey w1sh: there’s no reason you can’t use good ol’ PHP (because it’s by definition a templating language), but for JavaScript, and other langs, we have to do really ugly string concatenation like so:

        var myHTML = ” + MyTitle + ” + myParagraph ”;

        Wow that’s readable =P

        Now, imagine you have a very dynamic page, with 4-5 ajax updating widgets. You could code the template directly into the JS for each update, or you can use jQuery templating, Mustache, HAML, whatev, which provides a much cleaner separation of concerns.

        This becomes much more helpful the larger the application and the larger the team your working with.

      • w1sh

        @Brian: I see your point, but I suppose I can’t wrap my head around why JS would need a templating language. That’s probably just because I don’t know JS though.

        Although it is neat that it’s a cross-language templating framework. :)

  • http://www.careerfield.org Careerfield

    Thanks for the useful code and advice on implementing it.

  • http://marcusandre.de/ Marcus

    i don’t know if it’s a good practice to use javascript for such things. there is also a php version of mustache, which is maybe the better practice. perhaps it’s just my opinion.

    • http://brianegan.com Brian Egan

      Hi Marcus,

      I’d recommend checking out JavaScriptMVC and reading about Thin Server Architecture. They talk about when it’s a good idea to move your templating/other advanced logic to the client-side, and what the advantages are.

      From what I understand, it’s not “better” one way or the other — there are valid use cases for server-side and client-side templating, just depending on your app.

      Cheers,
      Brian

      • http://marcusandre.de/ Marcus

        Hi Brian,

        thank you for the reply. I think that you’re right, but I thought it wouldn’t be that good to use javascript, because what happens when the client has javascript deactivated? Or sth. in that way.

        But I think I accept your advice and hit some books about Thin Server Architecture. :)

        and … excuse my bad english. :D

      • http://brianegan.com Brian Egan

        Hey Marcus,

        Good call, you always want to make sure your site is functional without JavaScript, which is one reason something like Mustache or HAML is so awesome.

        You can write the exact same templates for your front and back-end code. So if the JS is disabled, use regular old links + PHP to generate new pages instead of dynamic links + ajax requests.

        Haha, and dont’ worry — you’re English is just as good as my PHP: it gets the job done =)

  • http://www.helloeverything.co.uk Web Designer, Leicester

    Thanks for posting, i learned a lot from it, especially as im moving more into development.

  • alphacoder

    Is it just me or is that link in the first sentence pointing back to this same tut?

    I would have thought it would point to the tut being referenced in the text, that is, the tut on Microsoft’s JQuery Template plugin.

  • http://www.richardkotze.com Richard Kotze

    Nice – its amazing how simple Mustache template is to use and how much sense it makes. Great stuff thanks for the quick tutorial.

  • http://www.vishu.net/wordpress Vishu

    I love the video tips here.. all of them! :D

  • http://aaroncruz.com aaron

    Check this out. Not even a mention of you. And they made it super ugly.
    http://blancer.com/tutorials/93091/quick-tip-using-the-mustache-template-library/
    Oh, and have you seen handlebar or jade?

  • Guillaume

    Great tut!

    Just one question, is there any way to use external templates with mustache.js? ie.: $.mustache(‘templates/template.ms’, result) ? (I’m using the jquery wrapped version)

    Thanks!

  • http://joreteg.com Henrik Joreteg

    If you’re working with jQuery there’s also http://icanhazjs.com which is a wrapper for working with and managing the mustache.js templates you have in your page.

    You just include icanhaz.js in your page (it includes mustache).

    Create templates in script tags of type text/html in your page like so:

    <script id=”user” type=”text</html”>
    <li>
    <p class=”name”>Hello I’m {{ name }}</p>
    <p><a href=”http://twitter.com/{{ twitter }}”>@{{ twitter }}</a></p>
    </li>
    </script>

    Then, just retrieve your populated template as a jQuery object ready to be used:

    // I Can Haz User?
    var user = ich.user(user_data_object)

  • http://joewlarson.com Joe Larson

    I’m a bit late to this party but stumbled onto the article after I wrote my own article about Mustache (http://joewlarson.com/blog/2011/02/06/mustache-templates/).

    Anyway, to answer people wondering why you’d want templating in the browser, I’ll answer: for any kind of Ajax app it’s faster and cleaner code than the two obvious alternatives of having to pull full HTML from your server or constructing HTML using DOM apis or embedding HTML all over your Javascript code.

    If your data set is being manipulated on the client end and you need to regenerate HTML on the fly, this is a very useful way to do it. Or, if you want to pull data in JSON and then do HTML generation on the client, this is generally a much faster way to go. I have my own HTML template library and I’ve done some pretty extensive testing on this. I will have to see how mustache compares, but superficially so far the results are similar.

  • http://www.seniorwebdesigner.com Mohamed Alaa

    Just wondering, Can we use Mustache in WordPress?

    • http://DennisSmolek.com DennisSmolek

      @Mohamed,

      The company I started for uses them for WP. They are doing some really intense paradigm changes to the way we write our templates. We use both the PHP and js version of Mustache to write single templates for both server side and once we make it to the client. Also, they have developed some great layouts that use the template system to display stuff much quicker. The motto is code once, reuse often.

      I’ll admit though it is a hard swallow to add the step but its starting to grow on me.

  • Zoran Ivancevic

    For people asking what is this for, try to do a bigger project, you will soon see a good reason for templating, if you want your code to be maintainable.

    On the other hand, there is one huuuuuge advantage in mustache templates, unlike most of other templating engines. You can use the same template for client and servers side (via partials, in PHP at least). Really nice way of doing a lot of ajaxing with no need of html duplication

  • http://www.wesbos.com Wes Bos

    Looks like you left out your muti-line escaping in this tutorial.

    When doing javascript on multi lines, use this:

    template = ” \
    {{name}} \
    {{#sites}} \
    {{#url}} {{.}} {{/url}} \
    {{/sites}} \
    “;

  • http://www.wesbos.com Wes Bos

    Looks like you left out your muti-line escaping in this tutorial.

    When doing javascript on multi lines, use this:

    template = ” \
    {{name}} \
    {{#sites}} \
    {{#url}} {{.}} {{/url}} \
    {{/sites}} \
    “;

  • Enrique García

    @Wes Bos: I noticed the same as you.

    In my case I opted for the array-and-join solution:

    template = [
    '{{name}}',
    '{{#sites}}',
    ' {{#url}} {{.}} {{/url}}',
    '{{/sites}}'
    ].join(‘\n’);

    This ensures the newlines are conserved (some browsers remove them when they are escaped).

  • Dave Porter

    I’ve just started playing around with this, and I have some other examples working, but this one only displays the H1 !
    What actually fires the mustache stuff ?
    Should the document.write happen automatically ?
    TIA, Dave

  • dlstone

    thank you too much,it’s very helpful for me.

  • Michael Calkins

    Link at top is broken.

    Not long ago, I demonstrated how to use the Mustache, which is just as easy to use.

  • Mike McLin

    Just created a video on sharing Mustache templates between PHP and JavaScript. I build a Twitter Bootstrap Alert template in the video. You can find it here: http://mikemclin.net/mustache-templates-for-php-and-javascript/