knockout.js loading templates at runtime

前端 未结 1 500
野趣味
野趣味 2021-02-09 02:20

I am using knockout.js with its inbuilt templating system. I define the templates as so:



        
相关标签:
1条回答
  • 2021-02-09 03:16

    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

    0 讨论(0)
提交回复
热议问题