0

I want to use knockout's renderTemplate function in a requireJS project/module.

I want to load the templates via the !text or !tmpl plugin.

Currently I end up with: "Uncaught Error: Cannot find template with ID ..."



A normal call would look like this:

ko.renderTemplate('personTmpl', { name:"test1" });


But this will search the DOM for something like:

<script id="personTmpl" type="text/javascript"/>

And thereby create a dependency on existing dom-nodes


But since I am building a requirejs-module, which looks like this (simplified & not working):

define(["knockout",
    "tmpl!templates/persons.html",
    "text!templates/persons.html",
    ],function(ko, personTmpl, personTmpl2){
        ko.renderTemplate('personTmpl', { name:"test1" });
        ko.renderTemplate('personTmpl2', { name:"test1" });
    });

Requirejs does not include my persons.html content as script-tag!

I can't find a way to make ko.renderTemplate consume anything other than script-IDs.

How can I make this work?

One solution might be loading the templates via requirejs and then pipe them into a script tag, like this:

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.id = "url";
$("head").append( script );*/

But I dont like this approach.


How to make the following work?

define(["knockout",
    "tmpl!templates/persons.html",
    "text!templates/persons.html",
    ],function(ko, personTmpl, personTmpl2){
        ko.renderTemplate(personTmpl, { name:"test1" });
        ko.renderTemplate(personTmpl2, { name:"test1" });
    });



So the question may break down to:

How to make this work: (or anything thats equivalent)?

ko.renderTemplate('<div>huhu</div>', { name:"test1" });

or this:

ko.renderTemplate($('<div>huhu</div>'), { name:"test1" });
Stephan
  • 11
  • 2
  • you might be interested in my library here: https://github.com/rniemeyer/knockout-amd-helpers. It lets you do `data-bind="template: 'myTemplate'"` and loads it using the `text` plugin automatically and allows you to configure the path and extension of the files. – RP Niemeyer Jan 28 '14 at 16:22
  • this sounds ***very promising!*** thx alot! (i was stuck here for quite some time) – Stephan Jan 28 '14 at 16:44

0 Answers0