-
Notifications
You must be signed in to change notification settings - Fork 2
API compile
Given a set of Mustache template fragment(s), this function will return a function that takes an associated data object which can be used to return the results of an interpolation. This function is useful when a particular Mustache template needs to be interpolated many times or if it contains complex template code. In these instances, it is much more performant than the render API function.
Mustache.compile(template)
Mustache.compile(template, 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 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.
The function returns a function with the following signature:
function(view)
Where
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.
At a minimum the template
parameter must be supplied:
var compiled = Mustache.compile('{{interpolate}}');
var result = compiled({ interpolate: 'Bugs Bunny' });
result === 'Bugs Bunny'; // true
When using partials in the entry point template, you must include the partials
argument as well:
var compiled = Mustache.compile('{{>a_partial}}', { a_partial: '{{interpolate}}' });
var result = compiled({ interpolate: 'Bugs Bunny' });
result === 'Bugs Bunny'; // true
Note that if the Mustache templates provided to the compile
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 compiled = Mustache.compile('{{=');
//compiled === ??
} catch (e) {
if (e instanceof Mustache.Error) {
// e contains information about the error
}
}