如何从handlebars.js部分加载多个模板 [英] How to load multiple templates from handlebars.js partial

查看:393
本文介绍了如何从handlebars.js部分加载多个模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以使用handlebars.js加载具有多个模板的部分文档,就像可以使用mustache.js和

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"

例如:

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

推荐答案

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>

这篇关于如何从handlebars.js部分加载多个模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆