【问题标题】:How to load multiple templates from handlebars.js partial如何从 handlebars.js 部分加载多个模板
【发布时间】:2016-05-04 09:41:23
【问题描述】:

有没有一种简单的方法来加载包含多个模板的部分,使用 handlebars.js,就像你可以使用 mustache.js 和 jQuery plugin from "jonnyreeves" 一样

例如:

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

【问题讨论】:

    标签: javascript jquery handlebars.js mustache rich-client-platform


    【解决方案1】:

    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>
    

    【讨论】:

    • 非常感谢 :) 这正是我的问题的解决方案。我认为缺少的链接是这部分content.filter("#test-template").html()
    • 是的,这是主要区别,还有 registerPartial 部分。
    猜你喜欢
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多