Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a partial in Mustache JS

I have an html template in a var template and an object in var obj.
I call my template in Javascript like this.

var html = Mustache.render(template, obj, {
  templateRef: "path/template"
});

If I console.log html, the original template display perfectly, but the partial (templateRef) section is not rendered at all.

In my template, I have a reference to the partial like this:

{{> templateRef}}

I tried to put the partial on the same level (Remove path), include extension (.mustache), etc. But nothing seems to work.

Anyone have an idea what I'm missing?

like image 220
Simon Arnold Avatar asked Dec 11 '22 05:12

Simon Arnold


2 Answers

It doesn't appear that Mustache.js supports specifying a partial by its path:

The object should be keyed by the name of the partial, and its value should be the partial text.

You'll have to retrieve the template's text and provide that to Mustache.render() (e.g., with jQuery):

$.get('path/template.mustache', function (partialTemplate) {

  var html = Mustache.render(template, obj, {
    templateRef: partialTemplate
  });

  // ...

}, 'text');
like image 157
Jonathan Lonowski Avatar answered Jan 01 '23 09:01

Jonathan Lonowski


Editing answer to relate to MustacheJS (not handlebars - my mistake). You should be able to pass the Partial template into the main template, like so:

var data = {
    firstName: "Christophe",
    lastName: "Coenraets",
    address: "1 Main street",
    city: "Boston",
    state: "MA",
    zip: "02106"
};

var template = "<h1>{{firstName}} {{lastName}}</h1>{{>address}}";
var partials = {address: "<p>{{address}}</p>{{city}}, {{state}} {{zip}}"};
var html = Mustache.to_html(template, data, partials);
$('#sampleArea').html(html);

JsFiddle: http://jsfiddle.net/LUvpM/
Reference: http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/

like image 39
kcent Avatar answered Jan 01 '23 09:01

kcent