8

我正在使用带有内置模板系统的 knockout.js。我这样定义模板:

<script type="text/html" id="subjectItemView">
   <span class="name" data-bind="text: subjectName" />
</script>

然后我使用模板的 id,因此将其作为脚本的一部分是必要的。

我的单页应用程序中有相当多的这些模板,并且最近开始使用 require.js 来加载仅在需要时才需要的脚本。我想对模板做同样的事情,最好使用 require.js 以便我的模块可以将模板列为依赖项。

我该怎么做呢?

4

1 回答 1

10

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

于 2012-09-21T01:53:33.677 回答