Marc Hellmuth Marc Hellmuth - 1 year ago 242
jQuery Question

How to load multiple templates from handlebars.js partial

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);

Answer Source

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

You can do it like this:


$(document).ready(function() {

  //Get template from server
  $.get("").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
      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 -->
<script id="test-template" type="text/x-handlebars-template">
  {{#each test}}
    {{> foo}}
    {{> bar}}

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

<script id="bar-partial" type="text/x-handlebars-template">
  <div class="bar">
    <div class="bar_foo">{{bar_foo}}</div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download