2

我用一些内部模板构建了一个 html 页面。见网址 jsfiddle:

http://jsfiddle.net/hoven002/jQTDH/

使模板外部化的最佳方法是什么以及如何?

问候,肯尼斯

4

2 回答 2

5

在我看来,最好的方法是使用这个插件:https ://github.com/ifandelse/Knockout.js-External-Template-Engine 。

它启用了一个新的模板引擎,该引擎将从外部文件中提取模板。它还有一些配置选项来确定从哪里提取模板。

于 2012-06-05T13:11:02.430 回答
2

我编写了一个加载模板的函数,除了 jQuery 之外没有任何依赖项。您必须<script>使用属性标记要动态加载的每个标签data-template-src,并将 HTML 文件的路径放在那里。以下是代码和示例。

警告:因为它使用 AJAX 加载模板,所以它需要一个 HTTP 服务器(它不能在本地使用file://协议)

/main.js

// Loads all the templates defined with the tag data-template-src.
// Returns a promise that fulfills when all the loads are done.
function loadTemplates() {
    var templateLoads = [];

    $('[data-template-src]').each(function () {
        var templateElement = $(this);
        var templateUrl = templateElement.attr('data-template-src');

        // Load the template into the element and push the promise to do that into the templateLoads array
        templateLoads.push(
            $.get(templateUrl)
            .done(function (data) {
                templateElement.html(data);
            })
        );
    });

    return $.when.apply($, templateLoads);
}

// When all templates are loaded, apply bindings
loadTemplates().done(function () {
    ko.applyBindings({}, document.getElementById("htmlDoc"));
});

/index.html

<html id="htmlDoc">
  <body>
    <div data-bind="template: { name: 'exampleTemplate' }"></div>
    <script type="text/html" id="exampleTemplate" data-template-src="/assets/exampleTemplate.html"></script>

    <script src="/jquery.js"></script>
    <script src="/knockout.js"></script>
    <script src="/main.js"></script>
  </body>
</html>

/assets/exampleTemplate.html

<h1>Hello world</h1>

<div data-bind="template: { name: 'exampleSubTemplate' }"></div>

/assets/exampleSubTemplate.html

<h2>How do you do?</h2>
于 2013-12-19T08:47:13.060 回答