Basics
can.mustache.Basics
Mustache templates are logic-less templates with a simple syntax. The goal with Mustache is to keep your templates as simple as possible.
Mustache templates are logic-less templates with a simple syntax. The goal with Mustache is to keep your templates as simple as possible.
Here's a quick example of what Mustache templates look like:
Given the following data object:
The template would render the following:
In general, it's best to try to ensure that the data passed to the template already has any logic applied to it. However, CanJS's Mustache implementation provides helper tags in addition to the basic tags which can be used for richer functionality where modifying the data ahead of time isn't viable.
Just like EJS, Mustache can be used for live binding templates. As opposed to EJS, however, Mustache will automatically inject the
attr()
calls on observable and compute objects to wire it up.Tags
Mustache templates are intended to be logic-less in that there are no
if
statements orfor
loops. Tags handle all of the data injection for the template, taking in a key reference and then converting the result to a string.Tags in Mustache are surrounded by double curly braces (a.k.a. mustaches) like
{{key}}
. In this example,key
references thekey
property on the context scope passed to the template.There are a number of basic tags that can be used to inject data into the template.
{{key}}
will render the value referenced within the tag, escaping any HTML:{{{key}}}
or{{&key}}
will render the value referenced within the tag unescaped:{{#key}}
followed by{{/key}}
signify a section. Sections will only render if thekey
references a value that is considered truthy. If the key is a reference to an object, it will also add a local context which can be referenced by tags within the section. Sections can also be used to iterate through an array, if that was the value referenced. In this example, the name will only be rendered if there is a person exists whom also has a name:{{^key}}
followed by{{/key}}
signify an inverse section. Inverted sections will only render if thekey
references a value that is considered falsey:{{>key}}
renders a partial template. Partials are used to nest other templates within another template:{{!key}}
are comment tags. Comments won't get rendered (they're similar to HTML comments):