3

mustache.js と「jonnyreeves」の jQuery プラグインを使用してできるように、handlebars.js を使用して、複数のテンプレートを含むパーシャルを簡単にロードする方法はありますか

例えば:

$.Mustache.load('./templates/greetings.htm').done(function () {
    $('body').mustache('simple-hello', viewData);
});
4

1 に答える 1

4

Handlebars.jsでは、各パーシャルを登録する必要があります。Handlebars.registerPartial

次のように実行できます。

Javascript

$(document).ready(function() {

  //Get template from server
  $.get("http://example.com/template.html").done(function(response) {
    var content = $($.parseHTML(response));

    //Compile main template
    var template = Handlebars.compile(content.filter("#test-template").html());

    //You need to register each partial
    Handlebars.registerPartial({
      foo: content.filter("#foo-partial").html(),
      bar: content.filter("#bar-partial").html()
    });

    //Your data
    var data = {
      "test": [{
        foo: "Foo",
        "foo_bar": "Foo-Bar",
        bar: "Bar",
        bar_foo: "Bar-Foo"
      }, {
        foo: "Foo2",
        "foo_bar": "Foo-Bar2",
        bar: "Bar2",
        bar_foo: "Bar-Foo2"
      }]
    };


    document.body.innerHTML = template(data);

  });

});

template.html

<!-- template.html -->
<script id="test-template" type="text/x-handlebars-template">
  {{#each test}}
    {{> foo}}
    {{> bar}}
  {{/each}}
</script>

<script id="foo-partial" type="text/x-handlebars-template">
  <div class="foo">
    <h2>{{foo}}</h2>
    <div class="foo_bar">{{foo_bar}}</div>
  </div>
</script>

<script id="bar-partial" type="text/x-handlebars-template">
  <div class="bar">
    <h2>{{bar}}</h2>
    <div class="bar_foo">{{bar_foo}}</div>
  </div>
</script>
于 2016-01-27T21:58:06.017 に答える