Search code examples
knockout.jsjquery-templates

Knockout.js: how to pre-compile string templates to insert in the DOM (ko_code) to work correctly?


I think my issue comes from using Knockout.js with "jquery.tmpl.1.0.0pre.js" where existing DOM script templates become pre-compiled? I'm trying to figure out how to pump external html templates in to a page (which I've done) but also get Knockout.js to use them (which currently fails with errors.) BTW, I'm applying Knockout bindings after all ajax calls complete.

Here's the steps I went through:

My first step: I moved the in-line html template to Javascript, which worked well including with Knockout.js:

$('#templates').append(
    '<script type="text/x-jquery-tmpl" id="DDLTmpl">' +
        '<select data-bind="options:options(),value:$item.data.value,' +
        'optionsCaption:caption(),optionsText:\'text\',optionsValue:\'value\'">'+
        '</select>' +
    '</script>');

Second step: I loaded the same HTML from a separate file from the same domain and inserted it in the DOM:

$.ajax({
    url: '/somewhere/Tmpl.htm',
    data: {},
    success: function(data) {
        $('#templates').append(
            $('<script type="text/x-jquery-tmpl" id="Tmpl" />').html(data)
         );
    },
    dataType: 'html'
});

This succeeded, but caused Knockout to get an "illegal character" error ');if(typeof(\'$\' + fns.fM)!=='undefined' && (\'$\'. Looking at the two templates in the DOM, one is encoded with this:

{{ko_code ((function() { return ko.templateRewriting.applyMemoizedBindings...

and the second appears as if the html were cut and pasted in the div as expected.

Do I need to pre-compile a template? How would I encode a template to work with Knockout.js?

My next step is to remove the jquery.tmpl.1.0.0pre.js dependency and use the native Knockout.js template engine (or doT.) I'm currently using Knockout 2.1.0.js.


Solution

  • Use the built in way of defining template sources instead, much easier.

    Ryan has a good article on it, http://www.knockmeout.net/2011/10/ko-13-preview-part-3-template-sources.html

    Or you can checkout how I did it for my KO Combobox binding

    https://github.com/AndersMalmgren/Knockout.Combobox