can-stache
Live binding Mustache and Handlebars-compatible templates.
stache([name,] template)
Processes the template and returns a renderer function. Use steal-stache to import template renderer functions with StealJS.
Parameters
- name
{String}
:Provides an optional name for this type that will show up nicely in errors. Files imported with steal-stache will use their filename.
- template
{String}
:The text of a stache template.
Use
Stache templates are a mustache and handlebars compatible syntax. Stache templates are used to:
- Convert data into HTML.
- Update the HTML when observable data changes.
- Enable custom elements and bindings.
The following creates a stache template, renders it with data, and inserts the result into the page:
import stache from "can-stache";
// renderer is a "renderer function"
const renderer = stache( "<h1>Hello {{subject}}</h1>" );
// "renderer functions" render a template and return a
// document fragment.
const fragment = renderer( { subject: "World" } );
// A document fragment is a collection of elements that can be
// used with jQuery or with normal DOM methods.
fragment; //-> <h1>Hello World</h1>
document.body.appendChild( fragment );
Render a template with observable data like DefineMaps or DefineLists and the resulting HTML will update when the observable data changes.
import DefineMap from "can-define/map/map";
const renderer = stache( "<h1>Hello {{subject}}</h1>" );
const map = new DefineMap( { subject: "World" } );
const fragment = renderer( map );
document.body.appendChild( fragment );
map.subject = "Earth";
document.body.innerHTML; //-> <h1>Hello Earth</h1>
There’s a whole lot of behavior that stache
provides. The following walks through
the most important stuff:
- Magic Tag Types - The different tag types like
{{key}}
and{{#key}}...{{/key}}
- Scope and Context - How key values are looked up.
- Expressions - Supported expression types like
{{helper arg}}
and{{method(arg)}}
- Template Acquisition - How to load templates into your application.
- Helpers - The built in helpers and how to create your own.
- Live Binding - How live binding works.
See also
can-view-scope is used by stache
internally to hold and lookup values. This is similar to
how JavaScript’s closures hold variables, except you can use it programmatically.
can-component and can-view-callbacks.tag allow you to define custom elements for use within a stache template. can-view-callbacks.attr allow you to define custom attributes.
can-stache-bindings sets up element and bindings between a stache template’s can-view-scope, component viewModels, or an element’s attributes.