how do you do template binding with "compiled" templates?

26 views
Skip to first unread message

jrw

unread,
Apr 18, 2011, 1:17:58 PM4/18/11
to KnockoutJS
Hi,

I'm really enjoying KO but have run into one issue. The issue for me
is more complex than the example below because I am dealing with
nesting but it basically boils down to not being able to use compiled
templates with data-bind="template..."

This example should display "Pa" 3 times but only does it twice. The
last <div data-bind='template: "peopleTemplate"'> </div> does not
work. Any ideas how to fix this?

<script id='peopleTemplate' type='text/html'>
${parentName}
</script>

<script type='text/javascript'>
var viewModel = {
parentName: "Pa"
};

ko.applyBindings(viewModel);

$.template("peopleTemplate2", "${parentName}");
$.tmpl("peopleTemplate2", viewModel).appendTo("body");
</script>

<div data-bind='template: "peopleTemplate2"'> </div>


<div data-bind='template: "peopleTemplate"'> </div>

<script id='peopleTemplate' type='text/html'>
${parentName}
</script>

<script type='text/javascript'>
var viewModel = {
parentName: ko.observable("Pa")
};

ko.applyBindings(viewModel);

$.template("peopleTemplate2", "${parentName}");
$.tmpl("peopleTemplate2", viewModel).appendTo("body");
</script>

<div data-bind='template: "peopleTemplate2"'> </div>

rpn

unread,
Apr 18, 2011, 1:52:58 PM4/18/11
to knock...@googlegroups.com
Currently, the jqueryTmplTemplateEngine requires that the template actually lives in a script tag.  This has come up before and I think that it is something that could possibly be addressed in Knockout.

As a workaround, you would currently need to add it to your document.  Internally KO uses a function like:

    function addTemplate(templateName, templateMarkup) {
        document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
    }

you could add it to your document, in any way that you want.  I usually do:

  function addTemplate(templateName, templateMarkup) {
        $("body").append("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
    }
  


jrw

unread,
Apr 18, 2011, 2:58:49 PM4/18/11
to KnockoutJS
Thank you. That work around seems like it will be ok for my situation.
Reply all
Reply to author
Forward
0 new messages