DoneJS StealJS jQuery++ FuncUnit DocumentJS
5.33.3
6.0.0 4.3.0 3.14.1 2.3.35
  • About
  • Guides
  • API Docs
  • Community
  • Contributing
  • Bitovi
    • Bitovi.com
    • Blog
    • Design
    • Development
    • Training
    • Open Source
    • About
    • Contact Us
  • About
  • Guides
  • API Docs
    • Observables
      • can-bind
      • can-compute
      • can-debug
      • can-define
      • can-define/list/list
      • can-define/map/map
      • can-define-backup
      • can-define-stream
      • can-define-stream-kefir
      • can-event-queue
      • can-kefir
      • can-list
      • can-map
      • can-map-compat
      • can-map-define
      • can-observable-array
      • can-observable-object
      • can-observation
      • can-observation-recorder
      • can-observe
      • can-simple-map
      • can-simple-observable
      • can-stream
      • can-stream-kefir
      • can-value
    • Views
      • can-attribute-observable
      • can-component
      • can-stache
        • Tags
          • {{expression}}
          • {{{expression}}}
          • {{#expression}}
          • {{/expression}}
          • {{else}}
          • {{<partialName}}
          • {{!expression}}
          • {{-expression-}}
        • Helpers
          • and
          • console
          • debugger
          • domData
          • eq
          • for(of)
          • portal
          • if
          • joinBase
          • let
          • not
          • or
          • switch
          • case
          • default
        • Expressions
          • Bracket Expression
          • Call Expression
          • Hash Expression
          • KeyLookup Expression
          • Literal Expression
        • Methods
          • addBindings
          • addConverter
          • addHelper
          • addLiveHelper
          • from
          • safeString
        • Key Operators
          • ~compute
          • ./current
          • ../parent
          • scope
          • scope/key
          • this
          • key
        • Pages
          • Expressions
          • Helpers
        • Types
          • getterSetter
          • helper
          • helperOptions
          • sectionRenderer
          • simpleHelper
          • view
        • Deprecated
          • Helper Expression
          • scope.vars
          • {{data name}}
          • {{#each(expression)}}
          • {{#is(expressions)}}
          • {{#unless(expression)}}
          • {{#with(expression)}}
          • registerConverter
          • registerHelper
          • registerPartial
          • Legacy Scope Behavior
          • {{^expression}}
          • {{>key}}
      • can-stache-bindings
      • can-stache-converters
      • can-stache-element
      • can-stache-route-helpers
      • can-view-autorender
      • can-view-callbacks
      • can-view-import
      • can-view-live
      • can-view-model
      • can-view-nodelist
      • can-view-parser
      • can-view-scope
      • can-view-target
      • steal-stache
    • Data Modeling
      • can-connect
      • can-connect-feathers
      • can-connect-ndjson
      • can-connect-tag
      • can-fixture
      • can-fixture-socket
      • can-local-store
      • can-memory-store
      • can-ndjson-stream
      • can-query-logic
      • can-realtime-rest-model
      • can-rest-model
      • can-set-legacy
      • can-super-model
    • Routing
      • can-deparam
      • can-param
      • can-route
      • can-route-hash
      • can-route-mock
      • can-route-pushstate
    • JS Utilities
      • can-assign
      • can-define-lazy-value
      • can-diff
      • can-globals
      • can-join-uris
      • can-key
      • can-key-tree
      • can-make-map
      • can-parse-uri
      • can-queues
      • can-string
      • can-string-to-any
      • can-zone-storage
    • DOM Utilities
      • can-ajax
      • can-attribute-encoder
      • can-child-nodes
      • can-control
      • can-dom-data
      • can-dom-events
      • can-dom-mutate
      • can-event-dom-enter
      • can-event-dom-radiochange
      • can-fragment
    • Data Validation
      • can-define-validate-validatejs
      • can-type
      • can-validate
      • can-validate-interface
      • can-validate-legacy
      • can-validate-validatejs
    • Typed Data
      • can-cid
      • can-construct
      • can-construct-super
      • can-data-types
      • can-namespace
      • can-reflect
      • can-reflect-dependencies
      • can-reflect-promise
      • can-types
    • Polyfills
      • can-symbol
      • can-vdom
    • Core
    • Infrastructure
      • can-global
      • can-test-helpers
    • Ecosystem
    • Legacy
  • Community
  • Contributing
  • GitHub
  • Twitter
  • Chat
  • Forum
  • News
Bitovi

addHelper

  • Edit on GitHub

Register a global helper function.

stache.addHelper(name, helper)

Registers a global helper function with stache that always gets passed the value of its arguments (instead of value observables like addLiveHelper). Pass the name of the helper followed by the function to invoke. See Helpers for more details on using helpers.

import {stache} from "can";

stache.addHelper( "upper", function( str ) {
  return str.toUpperCase();
} );

var frag = stache(`{{ upper(name) }}`)( {name: "Justin"} );

document.body.append(frag); // Outputs: `JUSTIN`

Parameters

  1. name {String}:

    The name of the helper.

  2. helper {simpleHelper(arg..., options)}:

    The helper function. The helper function will be called with a helperOptions argument if the helper is called first level:

    {{# helper() }} HI {{/ helper }}
    

stache.addHelper(helpers)

Register multiple helpers with stache that always get passed the value of its arguments (instead of value observables).

Pass an object where the key is the name of a helper and the value is the callback.

stache.addHelper({
    upper: function(str) {
        return str.toUpperCase();
    },
    lower: function(str) {
        return str.toLowerCase();
    }
});

Parameters

  1. helpers {Object}:

    an Object of name/callback pairs.

Use

Global helper functions should be used to enhance stache with useful functionality common to most of your application. Examples of custom helpers might include:

  • Converting a raw Date to a more user friendly timestamp. {{ timestamp(birthday) }}
  • Internationalization. {{ i18n('Hello') }}
  • Convert markdown into HTML. {{ markdown(comment) }}

Stache includes a number of built-in helpers, but custom helpers can be added as well.

You can register your own global helper with the addHelper or addLiveHelper methods.

addHelper calls the registered helper function with values, while addLiveHelper calls the registered helper function with computes if observable data is passed. addHelper is easier to use for basic helper functionality.

Localization is a good example of a custom helper you might implement in your application. The below example takes a given key and returns the localized value using jQuery Globalize.

stache.addHelper( "l10n", function( str, options ) {
    return typeof Globalize !== "undefined" ?
        Globalize.localize( str ) :
        str;
} );

In the template, invoke the helper by calling the helper name followed by any additional arguments.

<!-- Template -->
<span>{{ l10n('mystring') }}</span>
<!-- Result -->
<span>my string localized</span>

Helper Arguments

The type of arguments passed to a addHelper function depends on how the helper was called and the values passed to the helper. If the helper is called:

  • directly within the magic tags like {{ helper() }}, it will be called with an additional helperOptions argument.
  • within another expression like {{ outer( helper() ) }}, it will be called with the arguments visible from stache.

The following demonstrates this:

import {stache} from "can";

stache.addHelper( "argumentsLength", function() {
    return arguments.length;
} );

stache.addHelper( "echo", function(value) {
    return value;
} );

var frag = stache(`
    <p>{{ argumentsLength(0,1) }} should be 3</p>
    <p>{{ echo( argumentsLength(0,1) ) }} should be 2</p>
`)();

document.body.append(frag);

Evaluating Helpers

If you want to use a helper with a {{#expression}} tag, you should call options.fn(context) in your return statement. This will return a document fragment or string with the resulting evaluated subsection.

Similarly, you can call options.inverse(context) to evaluate the template between an {{else}} tag and the closing tag.

For example, when a route matches the string passed to our routing helper it will show/hide the text.

import {stache, DefineMap} from "can";

stache.addHelper( "isReady", function( status, options ) {

    if ( ["new","backlog"].indexOf(status) !== -1 ) {
        return options.fn();
    } else {
        return options.inverse();
    }
} );

var data = new DefineMap({status: "new"});
var frag = stache(`
    {{# isReady(status) }}
        I am ready.
    {{else}}
        Wait!
    {{/ isReady }}

    <select value:bind="status">
        <option>new</option>
        <option>backlog</option>
        <option>assigned</option>
        <option>complete</option>
    </select>
`)(data);

document.body.append(frag);

Advanced Helpers

Helpers can be passed normal objects, native objects like numbers and strings, as well as a hash object. The hash object will be an object literal containing all ending arguments using the key=value syntax. The hash object will be provided to the helper as options.hash. Additionally, when using {{#expression}} tags with a helper, you can set a custom context by passing the object instead of this.

stache.addHelper( "exercise", function( group, action, num, options ) {
    if ( group && group.length > 0 && action && num > 0 ) {
        return options.fn( {
            group: group,
            action: action,
            where: options.hash.where,
            when: options.hash.when,
            num: num
        } );
    } else {
        return options.inverse( this );
    }
} );
{{#exercise(pets, 'walked', 3, where='around the block' when=time)}}
    Along with the {{#group}}{{.}}, {{/group}}
    we {{action}} {{where}} {{num}} times {{when}}.
{{else}}
    We were lazy today.
{{/exercise}}
{
    pets: [ "cat", "dog", "parrot" ],
    time: "this morning"
}

This would output:

Along with the cat, dog, parrot, we walked around the block
3 times this morning.

Whereas an empty data object would output:

We were lazy today.

CanJS is part of DoneJS. Created and maintained by the core DoneJS team and Bitovi. Currently 5.33.3.

On this page

Get help

  • Chat with us
  • File an issue
  • Ask questions
  • Read latest news