Dev*_*ate 22 templates knockout.js
我找到了加载外部模板的引擎,插件和函数,但我想知道是否有更简单的方法.像这样的东西?
templates.html
<script id="testTemplate" type="text/html">
<div>this is a div</div>
</script>
Run Code Online (Sandbox Code Playgroud)
的index.html
<div id="templateContainer"></div>
<script>
$(document).ready(function() {
$("#templateContainer").load("templates.html");
}
</script>
Run Code Online (Sandbox Code Playgroud)
这会有用吗?有没有"陷阱"?
Mic*_*est 28
这是我用来加载包含模板集合的模板文件:
var loadTemplateCollection = function(file, success) {
$.get('templates/' + file + '.html', function(templates) {
$('body').append('<div style="display:none">' + templates + '<\/div>');
success();
});
};
Run Code Online (Sandbox Code Playgroud)
这是我使用此功能的示例:
self.loadPage = function () {
if (!self.isLoaded()) {
loadTemplateCollection('uploadwizard', function() {
self.isLoaded(true);
self.uploadWizard();
});
}
}
Run Code Online (Sandbox Code Playgroud)
你的观点看起来像这样(if
很重要):
<div data-bind="template: {'if': isLoaded, name: 'uploadwizard', data: wizard}"></div>
Run Code Online (Sandbox Code Playgroud)
这是我用来加载新的页面视图.我觉得使用非常简单:
var template = 'template.html';
var targetID = 'container';
var partialVM = {data : 1};
var load = function (template, targetID, partialVM) {
$.ajax(template, { async: false })
.success(function (stream) {
$('#' + targetID).html(stream);
ko.applyBindings(partialVM, document.getElementById(targetID));
}
);
};
Run Code Online (Sandbox Code Playgroud)
但在我的html模板中,我没有脚本元素,只是一个简单的div作为根元素.
我希望它有所帮助.