Mustache Templating: nested templates

Harry picture Harry · Jul 27, 2011 · Viewed 20.1k times · Source

How can I use a nested template within mustache? Is there a way to do the same?

var tmpl="{{#data}} 
{{values}}
Name: {{name}}
//{{another_templ({{name.value}})}}
{{/values}}
{{/data}}"

Hope you guys got the question. I have not added the escape character for js validity since code is split across different lines.

Answer

marc picture marc · Jul 27, 2011

You could use a lambda to nest the template:

function nested_template(template_string, translate) {
  return function() {
    return function(text, render) {
      return Mustache.to_html(template_string, translate(render(text)));
    };
  };
}

var template_string = 
  "{{#data}}"+
    "{{values}}"+
      "Name: {{name}}"+
      "{{#another_templ}}{{name}}{{/another_templ}}"+
    "{{/values}}"+
  "{{/data}}";

var another_template_string = "<b>{{name}}</b>"; // for example

var view = {
  data: {
    values: {
      name: "Test"
    }
  },
  another_templ: nested_template(another_template_string, function(text) {
    return {name: text};
  });
};

var result = Mustache.to_html(template_string, view);