jsFiddle Example: Loading Mustache Partial Templates Via Ajax

Mustache is a great, simple, templating language, but the JS implementation (https://github.com/janl/mustache.js) doesn't make it clear that not only can you load partial templates dynamically, you can load them via Ajax (just not asynchronously). This is an example of using a function instead of an object as the partial argument to Mustache's .render() method.

This example has a bit of bit of logic to work around jsFiddle's limitations. For example, in order to let jsFiddle spoof an Ajax call, we need to supply the template data at the time the Ajax call is made, and therefor, the templates must reside in the HTML. In the real world the point of this would be to place each template in its own .html file, and the templateLoader() would be making get requests to load their content directly.



Pere's Gravatar Why a comma after 'var result = '','?
Jon Hartmann's Gravatar @PERE: Good question :) Its because I'm using a single line notation to create multiple variables. For example, if you write "var x = 3, y =4;" you get to variables, x and y with the respective values. You don't have to do that on a single line though, so in this case I broke it up to create "result" and "getTemplate" as variables.

The value "getTemplate" isn't used in the function though, so saving a reference to it isn't really necessary. You can just change it to a semi-colon and delete the "getTemplate =" part on the next line and it will work fine.
Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me.

Post a job. Find one. authenticjobs.com

Interested in becoming a sponsor? Contact me.