jQuery.mustache: more than just a jquery plugin


jquery.mustache let you write your Mustache.js templates in plain text files and then combine them in one JS file (a jQuery plugin) making it easy to render your templates. It also helps you dealing with i18n issues in your templates.


The template "banner" in the file "":

    ## This is a comment line and will be ignored
    <div class="banner">
      Welcome to my site !
      <ul class="menu">
        <li><a href="#page1">Page1</a></li>
        <li><a href="#page2">Page2</a></li>


The template "page1" in the file "":

    <div class="page">
      <p>_("This is a i18n text of the page 1")</p>

The template "page2" in the file "":

    <div class="page">
      <p>_("This is a i18n text of the page 2")</p>

How you can render these templates in your JS code:

    $('body').renders('page1', {
      user: "Chuck Norris"

You don't have to specify your partials, you can use whatever template name you have written (here "banner").

How it works

jquery.mustache features a python script which you run once you have written or updated your templates files. This script generates one or more files named as template_en.js (for English version here) plus generate/update i18n (po/mo) files using xgettext / msgfmt.

You include the generated file in your page as a regular js file, and then you can use the "renders" function on jQuery elements!

The generated file looks like:

    ;(function($) {
      var TEMPLATES = {"banner": "<div class=\"banner\">...</div>", "page1": "...", "page2": "..."};
      $.fn.renders = function(template_name, data) {
        var template = TEMPLATES[template_name];
        if(!template) throw new Error('Undefined template: ' + template_name);
        return $(this).html(Mustache.to_html(template, data || {}, TEMPLATES));

You can see a working example in the example directory. Just go there and type "make" to see it in action.

Have fun and don't hesitate to comment / report issues…

jquery.mustache GitHub page:

blog comments powered by Disqus