How to load multiple templates from handlebars.js partial

狂风中的少年 提交于 2019-12-21 20:46:47

问题


Is there an easy way to load a partial, with multiple templates in it, using handlebars.js, just like you can do it using mustache.js and the jQuery plugin from "jonnyreeves"

e.g:

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

回答1:


In Handlebars.js you need to register each partial, using Handlebars.registerPartial

You can do it like this:

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>


来源:https://stackoverflow.com/questions/35037348/how-to-load-multiple-templates-from-handlebars-js-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!