Knockout.js在运行时加载模板 [英] knockout.js loading templates at runtime
问题描述
我正在使用带有内置模板系统的kickout.js.我这样定义模板:
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>
然后我使用模板的ID,因此有必要将其作为脚本的一部分.
I then use the id of the template so having this as part of the script is a necessity.
在我的单页应用程序中,我有很少的这些模板,并且最近转移到使用require.js来加载仅在需要时才需要的脚本.我想对模板做同样的事情,最好使用require.js,以便我的模块可以将模板列为依赖项.
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.
我该怎么做?
推荐答案
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.
我的代码如下:
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;
});
}
};
我使用的stringTemplateEngine看起来像: https://github.com. com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js
The stringTemplateEngine that I use looks like: https://github.com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js
这篇关于Knockout.js在运行时加载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!