knockout.jsko-custom-binding

Custom binding handler, render binding from string template


I making a custom binding with a row template that should be optional. If the user does not supply a template id i want to use a default one, but it does not reside in a script tag in body, it's just a string on the options literal.

How can i use a string as template?

the default template should be really easy something like this

<span data-bind="text: name"></span>

I've tried the ko.renderTemplate but it does only take id's to script tags

ko.renderTemplate(template, bindingContext.createChildContext(data), null, row, "replaceChildren");

Update Just got a notification about this question, and saw that there were people suggestion injecting the template to the dom and use the standard script tag provider. But this does not take into account that the user can override the default template source (Common scenario with single plage applications. I use this way, that first tries the default template provider and then fallbacks to the string template source like this

var engines: {}
var renderTemplate = function (element, template, data, bindingContext) {
    var engine = engines[template];

    var success = false;
    do {
        try {
            ko.renderTemplate(template, bindingContext.createChildContext(data), engine, element, "replaceChildren");
            success = true;
            engines[template] = engine;
        } catch(err) {
            if (engine != null)
                throw "Template engine not found";

            engine = { templateEngine: stringTemplateEngine };
        }

    } while (!success)
};

Full code and stringTemplateEngine code can be found here https://github.com/AndersMalmgren/Knockout.Combobox/blob/master/src/knockout.combobox.js#L297


Solution

  • To render templates from strings you will need to write a custom template source as described here.

    Hope this helps.