22

外部テンプレートをロードするためのエンジン、プラグイン、および関数を見つけましたが、それを行うためのより簡単な方法があるかどうか疑問に思っています。このようなもの?

templates.html

<script id="testTemplate" type="text/html">
 <div>this is a div</div>
</script>

index.html

<div id="templateContainer"></div>
<script>
    $(document).ready(function() {
         $("#templateContainer").load("templates.html");
    }
</script>

これは機能しますか?「落とし穴」はありますか?

4

4 に答える 4

29

テンプレートのコレクションを含むテンプレート ファイルを読み込むために使用するものは次のとおりです。

var loadTemplateCollection = function(file, success) {
    $.get('templates/' + file + '.html', function(templates) {
        $('body').append('<div style="display:none">' + templates + '<\/div>');
        success();
    });
};

この関数を使用する例を次に示します。

self.loadPage = function () {
    if (!self.isLoaded()) {
        loadTemplateCollection('uploadwizard', function() {
            self.isLoaded(true);
            self.uploadWizard();
        });
    }
}

ビューは次のようになります (これifは重要です)。

<div data-bind="template: {'if': isLoaded, name: 'uploadwizard', data: wizard}"></div>
于 2013-06-12T20:24:49.357 に答える