Using mustache templates with knockout.js

Alex KeySmith picture Alex KeySmith · Sep 19, 2011 · Viewed 8k times · Source

I wish to use knockout.js, but unfortunately I cannot use jquery-tmpl due to the prequisite of jquery 1.4.2, which (I won't go into it here) we cannot upgrade to.

Has anyone got any tips on getting started using Mustache templates with knockout? I've been finding it tricky to find any information regarding it.

Answer

WTK picture WTK · Sep 19, 2011

Update I've released initial version of template engine for knockout js that is using mustache as a template library. You can check it out at https://github.com/WTK/ko.mustache.js


Have you seen this part of documentation http://knockoutjs.com/documentation/template-binding.html ? Especially take a closer look at the Note 8 which points you to check the jqueryTmplTemplateEngine.js in the knockout source code (to spare you the effort of searching, its this one: https://github.com/SteveSanderson/knockout/blob/master/src/templating/jquery.tmpl/jqueryTmplTemplateEngine.js).

I just took a glance at source of that file, but everything seems to be quite simple. You have to define couple of callback functions that are (I assume) called by knockout js when needed.

Those functions include:

function renderTemplateSource(templateSource, bindingContext, options) {}
function createJavaScriptEvaluatorBlock(script) {}
function addTemplate(templateName, templateMarkup) {}

Check what those functions return when using jquery.tmpl and try to mimic their behavior whilst using moustache instead.