API render - thegrandpoobah/mustache.js GitHub Wiki
API: Mustache.render
Description
Given a set of Mustache template fragment(s) and an associated data object, this function will return the result of the interpolation.
Signatures
Mustache.render(template, view)
Mustache.render(template, view, partials)
Mustache.render(template, view, partials)
The template parameter specifies the "entry point" into the Mustache template and must be present. From this template, you can reference other template fragments using the partials parameter. The format of this string must match the Mustache Syntax.
The view parameter specifies the associated data object that the interpolation is to run on. All JavaScript constructs are accepted in for this key/value pair. That is, this parameter is not necessarily just a JSON object, functions and Date objects are also accepted.
The partials parameter is a key/value pair of Mustache template fragments. The keys are the partials specified in the template Mustache fragment or the partials specified in other partials.
Examples
At a minimum the template and view parameters must be supplied:
var result = Mustache.render('{{interpolate}}', { interpolate: 'Bugs Bunny' });
result === 'Bugs Bunny'; // true
When using partials in the entry point template, you must include the partials argument as well:
var result = Mustache.render('{{>a_partial}}', { interpolate: 'Bugs Bunny' }, { a_partial: '{{interpolate}}' });
result === 'Bugs Bunny'; // true
Exceptions
Note that if the Mustache templates provided to the render function do not conform to the Mustache syntax, the function will throw a Mustache.Error specifying where in the code block it failed. Therefore, it is prudent to wrap the compile call in a try/catch block:
try {
var result = Mustache.render('{{=', {a: 'Bugs Bunny'});
//result === ??
} catch (e) {
if (e instanceof Mustache.Error) {
// e contains information about the error
}
}
Notes
If the same Mustache template/partial set needs to be interpolated multiple times, it is much more performant to use the Mustache.compile API function instead.