Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mustache templates with knockout.js

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.

like image 687
Alex KeySmith Avatar asked Sep 19 '11 09:09

Alex KeySmith


People also ask

Is mustache a template engine?

Mustache is a logicless template engine for creating dynamic content like HTML, configuration files among other things.

Is mustache a templating engine for Node js?

Mustache is a logic-less node. js templating engine syntax. It can be used for HTML, config files, source code – anything. Moreover, it works by expanding tags in a template using values provided in a hash or object.

How can you bind data to templates?

Bind properties in a component's template to properties in the component's JavaScript class. In the template, surround the property with curly braces, { property } . To compute a value for the property, use a JavaScript getter in the JavaScript class, get property (){} .

How does Ko identify the template block that needs to be rendered?

Shorthand syntax: If you just supply a string value, KO will interpret this as the ID of a template to render. The data it supplies to the template will be your current model object.


1 Answers

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.

like image 130
WTK Avatar answered Sep 18 '22 22:09

WTK