I am using knockout.js with its inbuilt templating system. I define the templates as so:
<script type="text/html" id="subjectItemView">
<span class="name" data-bind="text: subjectName" />
</script>
I then use the id of the template so having this as part of the script is a necessity.
I have a fair few of these templates in my single page application and have recently moved to using require.js to load the scripts that are required only when they are required. I would like to do the same with the templates, preferably using require.js so that my modules could list the templates as dependencies.
How do I do this?
I use the require.js text plugin: http://requirejs.org/docs/api.html#text. Once you have the template text, you can then append it to the page in a new script tag (with a type that is text/html
or something other than javascript).
I have been actually using a modified template engine that handles strings directly, so that I don't need to append extra script tags to the page.
My code looks something like:
this.activate = function() {
//load view model from the server
if (!this.loaded) {
require(["modules/" + name, "text!../templates/" + self.template + ".html"], function(Module, template) {
ko.templates[self.template] = template;
self.data(typeof Module === "function" ? new Module() : Module);
self.loaded = true;
});
}
};
The stringTemplateEngine that I use looks like: https://github.com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With