Live binding handlebars templates
JavaScript HTML

readme.md

can-stache

Build Status

Live binding handlebars templates

API

can-stache function

Live binding Mustache and Handlebars-comptable templates.

stache(template)

Processes the template and returns a renderer function that renders the template with data and local helpers.

  1. template {String}: The text of a mustache template.

  • returns {renderer(Object, Object, data, helpers)}: A renderer function that returns a live document fragment that can be inserted in the page.

simpleHelper {function(*..., can-stache.sectionOptions, arg..., options)}

A helper function passed to registerSimpleHelper.

function(*..., can-stache.sectionOptions, arg..., options)
  1. undefined {*}:

  2. undefined {can-stache.sectionOptions}:

  3. arg {*}: Arguments passed from the tag. After the helper name, any space seperated [can.stache.key keys], numbers or strings are passed as arguments.

    The following template:

    <p>{{madLib "Lebron James" verb 4}}</p>
    

    Rendered with

    {verb: "swept"}
    

    Will call a madLib helper with the following arguements.

    stache.registerSimpleHelper('madLib',
      function(subject, verb, number){
        // subject -> "Lebron James"
        // verb -> "swept"
        // number -> 4
    });
    

    Unlike [can.stache.helper] simple helpers will always pass the actual value (instead of a compute).

  4. options {can.stache.helperOptions}: An options object that gets populated with optional:

    • fn and inverse section rendering functions
    • a hash object of the maps passed to the helper
  • returns {String|function(HTMLElement)}: The content to be inserted into the template.

helper {function(*..., can.stache.sectionOptions, arg..., [options](#helperoptions-object))}

A helper function passed to registerHelper.

function(*..., can.stache.sectionOptions, arg..., options)
  1. undefined {*}:

  2. undefined {can.stache.sectionOptions}:

  3. arg {*|can.compute}: Arguments passed from the tag. After the helper name, any space seperated keys, numbers or strings are passed as arguments. [can.stache.key Keys] that read an observable value are passed as [can-compute.computed]'s.

  4. options {helperOptions}: An options object that gets populated with optional:

    • fn and inverse section rendering functions
    • a hash object of the maps passed to the helper
  • returns {documentFragment|String|can.contentArray|function(HTMLElement)}: The content to be inserted into the template.

helperOptions {Object}

The options argument passed to a helper function.

Object
  • fn {sectionRenderer(context, helpers)}: Renders the "truthy" subsection BLOCK. options.fn is only available if the helper is called as a section or inverse section like: {{#helper}} or `{{^helper}}. The subsection BLOCK's

    Available if the helper is called as a section or inverse section. [can.stache.helpers.sectionHelper section helper] is called. Call fn to render the BLOCK with the specified context.

  • inverse {sectionRenderer(context, helpers)}: Provided if a section helper is called with {{else}}. Call inverse to render the INVERSE with the specified context.

  • hash {Object<String,*|String|Number>}: An object containing all of the final arguments listed as name=value pairs for the helper.

    {{helper arg1 arg2 name=value other=3 position="top"}}

    options.hash = { name: .value, other: 3, position: "top" }

  • context {*}: The current context the stache helper is called within.

    var temp = stache(
      "{{#person.name}}{{helper}}{{/person.name}}");
    
    var data = {person: {name: {first: "Justin"}}};
    
    can.stache.registerHelper("helper", function(options){
    
      options.context === data.person //-> true
    
    })
    
    
    temp(data);
    
  • scope {can-view-scope}: An object that represents the current context and all parent contexts. It can be used to look up key values in the current scope.

    var temp = stache(
      "{{#person.name}}{{helper}}{{/person.name}}");
    
    var data = {person: {name: {first: "Justin"}}};
    
    stache.registerHelper("helper", function(options){
    
      options.scope.attr("first")   //-> "Justin"
      options.scope.attr("person")  //-> data.person
    
    })
    
    
    temp(data);
    
  • options {can.view-scope.Options}: An object that represents the local stache helpers. It can be used to look up [can.stache.key key] values

    var temp = stache("{{#person.name}}{{helper}}{{/person.name}}");
    
    var data = {person: {name: "Justin"}};
    
    stache.registerHelper("helper", function(options){
    
      options.options.attr("helpers.specialHelper") //-> function
    
    })
    
    
    temp(data, {
      specialHelper: function(){ ... }
    });
    

key {String}

A named reference to a value in the [can-view-scope scope] or [can.view-scope.Options helper scope] in a template.

String

A key specifies a value in the [can.view.Scope scope] or [can-view-scope.Options options] of a template being rendered. The key is used to look up a value in the scope.

What the key looks like changes the behavior of how a value is looked up in the scope. Keys can look like:

  • {{name}} - Single property name.
  • {{name.first}} - Multiple property names.
  • {{foo\\.bar}} - Single property name that includes a dot character.
  • {{./name}} - Single property in the current context.
  • {{../name}} - Single property in the parent context.
  • {{.}} or {{this}} - The current context.
  • {{../.}} - The parent context.
  • {{@key}} - Pass the value at key, even if it's a function or a compute.
  • {{~key}} - Pass a compute as the key's value instead of the value.
  • {{*variable}} - Reference a value in template scope.
  • {{%key}} - A special value that is added to scope. Examples:
    • {{%index}} - The index of a value in an array or [can.List].
    • {{%key}} - The property name of a value within an object or [can.Map].
    • {{%element}} - The element an event was dispatched on.
    • {{%event}} - The event object.
    • {{%viewModel}} - The viewModel of the current element.

sectionRenderer {function(context, helpers)}

Renders a section. These functions are usually provided as .fn and .inverse on a stache helper's options.

function(context, helpers)
  1. context {*|can-view-scope}: Specifies the data the section is rendered with. If a [can-view-scope] is provided, that scope is used to render the section. If anything else is provided, it is used to create a new scope object with the current scope as it's parent. If nothing is provided, the current scope is used to render the section.

  2. helpers {*|can-view-scope.Options}: Specifies the helpers the section is rendered with. If a [can-view-scope.Options] is provided, that scope is used to render the section. If anything else is provided, it is used to create a new scope object with the current helper scope as it's parent. If nothing is provided, the current helper scope is used to render the section.

  • returns {documentFragment|String}: Returns the rendered result of the helper. If the section is within a tag, like:

    <h1 {{#helper}}class='power'{{/helper}}>
    

    a String is returned.

    If the section is outside a tag like:

    <div> {{#helper}}<h2>Tasks</h2>{{/helper}} </div>
    

    a documentFragment is returned.

stache.registerHelper(name, helper)

The following template:

{{upper foo}}
stache.registerHelper("upper", function(str){
    return str.toUpperCase();
});
  1. name {String}: The name of the helper.
  2. helper {helper(*..., can.stache.sectionOptions, arg..., options)}: The helper function.

stache.registerSimpleHelper(name, helper)

  1. name {String}: The name of the helper.
  2. helper {can-stache.simplehelper}: The helper function.

stache.safeString(str)

  1. str {String}: A string you don't want to become escaped.

  • returns {String}: A string flagged by mustache as safe, which will not become escaped, even if you use {{{key}}}(triple slash).

{{key}}

  1. key {key}: A key that references one of the following:

    • A registered helper.
    • A value within the current or parent [can-stache.context context]. If the value is a function or [can.compute], the function's return value is used.
  • returns {String|function|*}:

    After the key's value is found (and set to any function's return value), it is passed to [can.view.txt] as the result of a call to its func argument. There, if the value is a:

    • null or undefined - an empty string is inserted into the rendered template result.
    • String or Number - the value is inserted into the rendered template result.
    • Function - A [can.view.hook hookup] attribute or element is inserted so this function will be called back with the DOM element after it is created.

{{{key}}}

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

  1. key {key}: A key that references a value within the current or parent context. If the value is a function or [can-compute.computed], the function's return value is used.

  • returns {String|function|*}:

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

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

  1. key {key}: A key that references a value within the current or parent [can-stache.context context]. If the value is a function or [can-compute.computed], the function's return value is used.

  • returns {String}:

    Depending on the value's type, the following actions happen:

    • Array or [can-list] - the block is rendered for each item in the array. The [can-stache.context context] is set to the item within each block rendering.
    • A truthy value - the block is rendered with the [can.stache.context context] set to the value.
    • A falsey value - the block is not rendered.

    The rendered result of the blocks, block or an empty string is returned.

{{&key}}

The {{&key}} tag is an alias for {{{key}}}, behaving just like {{key}} and {{helper}} but does not escape the result.

  1. key {key}: A key that references a value within the current or parent context. If the value is a function or [can-compute.computed], the function's return value is used.

  • returns {String|function|*}:

{{/key}}

Ends a {{#key}} or [can-stache.tags.sectionHelper {{#helper}}] block.

  1. key {key}: A key that matches the opening key or helper name. It's also possible to simply write {{/}} to end a block.

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

Render blocks of text if the value of the key is falsey. An inverted section syntax is similar to regular sections except it begins with a caret rather than a pound. If the value referenced is falsey, the section will render.

  1. key {key}: A key that references a value within the current or parent [can-stache.context context]. If the value is a function or [can-compute.computed], the function's return value is used.

  • returns {String}:

    Depending on the value's type, the following actions happen:

    • A truthy value - the block is not rendered.
    • A falsey value - the block is rendered.

    The rendered result of the block or an empty string is returned.

{{!key}}

The comment tag operates similarly to a <!-- --> tag in HTML. It exists in your template but never shows up.

  1. key {key}: Everything within this tag is completely ignored.

  • returns {String}:

{{#case expr}}BLOCK{{/case}}

Renders the BLOCK when expr matches the expr provided in the parent {{#switch expr}}.

  1. expr {can-stache.expression}: An expression or key that references a value.

  2. BLOCK {can-stache}: a template that will render if the case clause resolves.

  • returns {DocumentFragment}: A fragment, possibly containing the rendered BLOCK.

{{data name[ key]}}

Adds the current [can-stache.context context] to the element's [can-data].

  1. name {String}: The name of the data attribute to use for the context.

{{#default}}BLOCK{{/default}}

Renders the BLOCK if no [can.stache.helpers.case] blocks within the switch resolved.

  1. BLOCK {can.stache}: a template to be rendered.

  • returns {DocumentFragment}: A fragment, containing the rendered block.

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

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

  1. key {key}: A key that references a value within the current or parent context. If the value is a function or can.compute, the function's return value is used.

    If the value of the key is a [can.List], the resulting HTML is updated when the list changes. When a change in the list happens, only the minimum amount of DOM element changes occur.

    If the value of the key is a [can.Map], the resulting HTML is updated whenever attributes are added or removed. When a change in the map happens, only the minimum amount of DOM element changes occur.

  2. BLOCK {can.stache}: A template that is rendered for each item in the key's value. The BLOCK is rendered with the context set to the item being rendered.

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

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

  1. INVERSE {can-stache}: a stache template coverted to a function and set as the helper function's options argument's inverse property.

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

Calls a stache helper function or a function. For example:

The template:

<p>{{madLib "Lebron James" verb 4 foo="bar"}}</p>

Rendered with:

{verb: "swept"}

Will call a madLib helper with the following arguements:

stache.registerHelper('madLib',
  function(subject, verb, number, options){
    // subject -> "Lebron James"
    // verb -> "swept"
    // number -> 4
    // options.hash.foo -> "bar"
});
  1. helper {key}: A key that finds a helper function that is either registered or found within the current or parent [can-stache.context context].

  2. args {key|String|Number}: Space seperated arguments that get passed to the helper function as arguments. If the key's value is a:

    • [can-map] - A getter/setter [can.compute] is passed.
    • [can-compute.computed] - The can.compute is passed.
    • function - The function's return value is passed.
  3. hashProperty {String}:

    A property name that gets added to a helper options's hash object.

  4. hashValue {key|String|Number}: A value that gets set as a property value of the helper option argument's hash object.

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

Renders the BLOCK template within the current template.

  1. key {key}: A key that references a value within the current or parent context. If the value is a function or can.compute, the function's return value is used.

  2. BLOCK {can-stache}: A stache template.

  • returns {String}: If the key's value is truthy, the BLOCK is rendered with the current context and its value is returned; otherwise, an empty string.

{{@index [offset]}}

Insert the index of an Array or [can-list] we are iterating on with #each

  1. offset {Number}: The number to optionally offset the index by.

{{#is expr...}}BLOCK{{/is}}

Renders the BLOCK template within the current template.

  1. expr {can-stache.expression}: An expression or key that references a value within the current or parent

  2. BLOCK {can-stache}: A template that is rendered if the result of comparsion expr1 and expr2 value is truthy.

  • returns {DocumentFragment}: If the key's value is truthy, the BLOCK is rendered with the current context and its value is returned; otherwise, an empty string.

{{joinBase expr}}

Return an application-relative url for a resource.

  1. expr {can-stache.expression}: An expression or key that references a value within the current or parent scope.

  • returns {String}: An application-relative url.

{{@key}}

Insert the property name of an Object or attribute name of a can.Map that we iterate over with #each

{{#log [message]}}

Logs the context of the current block with an optional message.

  1. message {*}: An optional message to log out in addition to the current context.

{{#routeCurrent hashes}}SUBEXPRESSION{{/routeCurrent}}

Renders SUBEXPRESSION if the hashes passed to [can-route.current route.current] returns true. Renders the {{else}} expression if [can-route.current route.current] returns false.

  1. hashes {}: A hash expression like page='edit' recipeId=id.

  • returns {String}: The result of SUBEXPRESSION or {{else}} expression.

routeCurrent([hashes])

Calls [can-route.current can.route.current] with hashes and returns the result.

  1. hashes {}: A hash expression like page='edit' recipeId=id.

  • returns {Boolean}: Returns the result of calling [can-route.current route.current].

{{routeUrl hashes [,merge]}}

Passes the hashes to route.url and returns the result.

  1. hashes {}: A hash expression like page='edit' recipeId=id.

  2. merge {Boolean}: Pass true to create a url that merges hashes into the current [can-route] properties. Passing the merge argument is only available in undefined like routeUrl(id=itemId, true).

  • returns {String}: Returns the result of calling route.url.

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

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

The template:

<p>{{#countTo number}}{{num}}{{/countTo}}</p>

Rendered with:

{number: 5}

Will call the countTo helper:

stache.registerHelper('countTo',
  function(number, options){
    var out = [];
    for(var i =0; i < number; i++){
      var docFrag = options.fn({num: i+1});
      out.push( docFrag.textContent );
    }
    return out.join(" ");
});

Results in:

<p>1 2 3 4 5</p>
  1. helper {key}: A key that finds a helper function that is either registered or found within the current or parent [can-stache.context context].

  2. args {key|String|Number}: Space seperated arguments that get passed to the helper function as arguments. If the key's value is a:

    • [can-map] - A getter/setter [can-compute.computed] is passed.
    • [can-compute.computed] - The compute is passed.
    • function - The function's return value is passed.
  3. hashProperty {String}:

    A property name that gets added to a helper options's hash object.

  4. hashValue {key|String|Number}: A value that gets set as a property value of the helper option argument's hash object.

  5. BLOCK {stache}: A stache template that gets compiled and passed to the helper function as the options argument's fn property.

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

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

The template:

<p>The bed is
   {{#isJustRight firmness}}
      pefect!
   {{else}}
      uncomfortable.
   {{/justRight}}</p>

Rendered with:

{firmness: 45}

Will call the isJustRight helper:

stache.registerHelper('isJustRight',
  function(number, options){
    if(number > 50){
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
});

Results in:

<p>The bed is uncomfortable.</p>
  1. helper {key}: A key that finds a helper function that is either registered or found within the current or parent [can-stache.context context].

  2. args {key|String|Number}: Space seperated arguments that get passed to the helper function as arguments. If the key's value is a:

    • [can-map] - A getter/setter [can-compute.computed] is passed.
    • [can-compute.computed] - The compute is passed.
    • function - The function's return value is passed.
  3. hashProperty {String}:

    A property name that gets added to a helper options's hash object.

  4. hashValue {key|String|Number}: A value that gets set as a property value of the helper option argument's hash object.

  5. BLOCK {stache}: A stache template that gets compiled and passed to the helper function as the options argument's fn property.

  6. INVERSE {stache}: A stache template that gets compiled and passed to the helper function as the options argument's inverse property.

{{#switch expr}}BLOCK{{/switch}}

Renders the BLOCK with contextual {{#case expr}} and {{#default}} helpers.

  1. expr {can-stache.expression}: An expression or key that references a value that will be switched on.

  2. BLOCK {can-stache}: a template that is rendered, uses {{#case expr}} and {{#default}} helpers to match expr.

  • returns {DocumentFragment}: A fragment containing the rendered BLOCK.

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

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

  1. key {key}: A key that references a value within the current or parent context. If the value is a function or [can-compute.computed], the function's return value is used.

  2. BLOCK {can.stache}: A template that is rendered if the key's value is falsey.

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

Changes the context within a block.

  1. key {key}: A key that references a value within the current or parent context. If the value is a function or [can-compute.computed], the function's return value is used.

  2. BLOCK {can-stache}: A template that is rendered with the context of the key's value.

Contributing

Making a Build

To make a build of the distributables into dist/ in the cloned repository run

npm install
node build

Running the tests

Tests can run in the browser by opening a webserver and visiting the test.html page. Automated tests that run the tests from the command line in Firefox can be run with

npm test