• constructor

can.Mustache can/view/mustache

 

Logic-less mustache templates with live binding when used with can.Observes.

new can.Mustache(options)

Creates an instance of a mustache template. This is typically not used directly in favor of can.view or can.view.mustache.

Parameters

  1. options {Object}

    An options object with the following properties:

    • text {String}

      The text of the mustache template.

    • name {String}

      The name of the template used to identify it to debugging tools.

Use

Mustache and Handlebar templates are compatible with can.Mustache.

Mustache templates looks similar to normal HTML except they contain contain keys for inserting data into the template and sections to enumerate and/or filter the enclosed template blocks.

For example, the following renders a welcome header for a user and displays the number of messages.

Mustache Template

<script id="template" type="text/mustache">
    <h1>Welcome {{user}}!</h1>
    <p>You have {{messages}} messages.</p>
</script>

JavaScript

var data = new can.Observe({
    user: 'Tina Fey',
    messages: 0
});

var template = can.view("#template", data)
document.body.appendChild(template);

HTML Result

<h1>Welcome Tina Fey!</h1>
<p>You have 0 messages.</p>

To update the html using live-binding, change an observable value:

data.attr('message', 5)

This updates the text to say:

<p>You have 5 messages.</p>

can.Mustache provides a lot more functionality such as:

Tags

{{key}}

Insert the value of the key into the output of the template.

{{{key}}}

Behaves just like {{key}} and {{helper}} but does not escape the result.

{{#key}}BLOCK{{/key}}

Render blocks of text one or more times, depending on the value of the key in the current context.

{{/key}}

Ends a {{#key}} or {{#helper}} block.

{{^key}}BLOCK{{/key}}

Render blocks of text if the value of the key is falsey.

{{helper [args...] [hashProperty=hashValue...]}}

Calls a mustache helper function or a function.

{{#helper [args...] [hashName=hashValue...]}}BLOCK{{/helper}}

Calls a mustache helper function or a function with a block to render.

{{#helper [args...] [hashName=hashValue...]}}BLOCK{{else}}INVERSE{{/helper}}

Calls a mustache helper function or a function with a fn and inverse block to render.

{{#if key}}BLOCK{{/if}}

Renders the BLOCK template within the current template.

{{#helper}}BLOCK{{else}}INVERSE{{/helper}}

Creates an inverse block for a helper function's options argument's inverse property.

{{#each key}}BLOCK{{/each}}

Render the block of text for each item in key's value.

{{#unless key}}BLOCK{{/unless}}

Render the block of text if the key's value is falsey.

{{#with key}}BLOCK{{/with}}

Changes the context within a block.

{{data name}}

Adds the current context to the element's can.data.

{{>key}}

Render another template within the current template.