Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache Templating: nested templates

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.

like image 495
Harry Avatar asked Jul 27 '11 15:07

Harry


People also ask

What is in Mustache template?

The Mustache templates consist of tag names surrounded by { { } } (which resemble mustaches – hence the name) and are backed by a model object containing the data for the template.

What is Mustache syntax?

Mustache is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops.

How does a Mustache file work?

Mustache is a logic-less templating system. It permits you to use pre-written text files with placeholders that will be replaced at run-time with values particular to a given request.

Which is logic-less templates?

A logic-less template is a template that contains holes for you to fill, and not how you fill them. The logic is placed elsewhere and mapped directly to the template. This separation of concerns is ideal because then the template can easily be built with different logic, or even with a different programming language.


1 Answers

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);
like image 55
marc Avatar answered Sep 18 '22 14:09

marc