Initialisation Options
edit this pageThe following is an exhaustive list of initialisation options that you can pass to new Ractive(options), with full descriptions grouped below by category.
Note that any additional options will be added as properties of the instance, so you can create custom methods (e.g. for calling from templates):
var ractive = new Ractive({
myMethod: function () {
alert( 'my method was called' );
}
});
ractive.myMethod(); // triggers the alert
| Option | Category | Description |
|---|---|---|
| adapt | data | adaptors to use |
| adaptors | data | registry of available adaptors |
| append | placement | how to handle existing content in the dom |
| complete | transitions | fine-tune template placement in the dom |
| components | templating | components to include for use by the template |
| computed | data | computed properties to include |
| csp | parsing | output CSP compatible (inline functions for expressions) templates |
| css | templating | component only css to include on render |
| data | data | the data to bind to the template |
| decorators | templating | decorators to include for use by the template |
| delimiters | parsing | delimiters to use when parsing the template |
| easing | transitions | easing functions to use in transitions |
| el | placement | render to this element in the dom |
| enhance | placement | try to reuse existing DOM on intial render |
| events | templating | events to include for use by the template |
| interpolators | transitions | interpolators to use for animating values |
| isolated | data | prevent components from accessing parent data and registries |
| lazy | binding | don't bind to every keypress |
| magic | binding | data object getters and setters that update view |
| modifyArrays | binding | array modification methods update the view |
| noCssTransform | templating | prevent transformation of component css |
| noIntro | transitions | do not apply transitions on render |
| onchange | lifecycle events | event fired when data changes |
| oncomplete | lifecycle events | event fired once transitions have completed |
| onconfig | lifecycle events | event fired once all configuration options have been processed |
| onconstruct | lifecycle events | event fired immediately after new Ractive(...) |
| ondetach | lifecycle events | event fired each time ractive.detach() is called |
| oninit | lifecycle events | event fired when the instance is ready to be rendered |
| oninsert | lifecycle events | event fired each time ractive.insert() is called |
| onrender | lifecycle events | event fired each time the instance is rendered |
| onteardown | lifecycle events | event fired each time the instance is destroyed |
| onunrender | lifecycle events | event fired each time the instance is unrendered |
| onupdate | lifecycle events | event fired after ractive.update() is called |
| partials | templating | partials to include for use by the template |
| preserveWhitespace | parsing | don't normalize template whitespace |
| sanitize | parsing | remove designated elements and event attributes |
| staticDelimiters | parsing | one-time binding parsing delimiters |
| staticTripleDelimiters | parsing | one-time binding non-escaped parsing delimiters |
| stripComments | parsing | remove HTML comments from templates |
| template | templating | specifies the template to use |
| transitions | transitions | transitions to include for use by the template |
| transitionsEnabled | transitions | allow transitions |
| tripleDelimiters | parsing | non-escaped parsing delimiters |
| twoway | binding | prevent updates from the view back to the model |
Templating
template
Stringor (if preparsing)ArrayorObjectThe template to use. If this is a string, it must be valid (if meaningless, until rendered) HTML:
template: '<p>{{greeting}} world!</p>',Otherwise this must be the output of Ractive.parse(), usually precompiled for use in the browser:
template: parsedTemplates.foo,Or alternatively, you can pass an id selector string like
#myTemplate- in this case, Ractive will use the contents of a<script>tag whose ID ismyTemplate:template: '#myTemplate'See the 60 second setup for an example of this.
Make sure to set
type='text/ractive'on the<script>tag or the browser will try and execute the contents as javascript and you'll get an exception. Some text editors will highlighttype='text/html'as HTML, which can be useful and the browser will still ignore it for execution.If a function, the result of the function can be a string or a pre-parsed template.
partials
ObjectA
key: valuehash of partials that are specific to this instance, wherekeyis the name of the partial (as referenced within templates as{{>myPartial}}), andvalueis either a valid template string or the output of Ractive.parse().partials: { myPartial: "<p>I'm a partial!<p>" }The partial name used in the template can also be used to lookup the partial by ID. See Partials for more info.
components
ObjectA
key: valuehash of components that are specific to this instance, wherekeyis the name of the component (as referenced within templates as<my-component></my-component>), andvalueis a valid component created by Ractive.extend().components: { 'my-component': Ractive.extend({ template: '#componentTemplate', init: function () {...} }) }See Components for more info.
decorators
ObjectA
key: valuehash of decorators that are specific to this instance, wherekeyis the name of the decorator (as referenced within templates as<div decorator="myDecorator"></div>), andvalueis a is a decorator functions. See Decorators for more info.decorators: { 'myDecorator': function( node, fire) {...} }events
ObjectA
key: valuehash of event plugins that are specific to this instance, wherekeyis the name of the event (as referenced within templates as<button on-mycustomevent="fire"></button>), andvalueis the custom event plugin functions. See Writing event plugins for more info.events: { 'mycustomevent': function( node, fire) {...} }css
StringUsed on components to specify
cssstyles to be inserted into the document.noCSSTransform
BooleanDefaults to
false. Prevents component css from being transformed with scoping guids.
DOM Placement
el
StringorHTMLElementor jQuery-like collectionDirectives for the element to render to. Use
appendoption (see below) to control whether existing content is replaced.
stringid or selector, see valid selectorsel: '#container'HTMLElementDOM elementel: document.body- any
objwhereobj[0]is anHTMLElement, see jquery collectionsel: $('#container')enhance
BooleanDefaults to
false. Whether or not to try to reuse the existing DOM in the target element when rendering a.k.a. progressive enhancement. This allows you to serve the fully rendered page and then render the Ractive template at load over the pre-rendered page without completely wiping out the existing content. There are a few limitations surrounding text nodes, but all matching elements will be reused.This option cannot be used with
append.To expand on the limitations with text nodes, since HTML does not have a markup representation for individual adjacent text nodes where the DOM does, the loaded DOM will have all text nodes merged when the document loads from the server. Ractive needs individual adjacent text nodes in certain situations like
outer text {{#if foo}}inner text{{/if}}. The'outer text 'text node is always present, and iffoobecomes truthy, an additional text node will be inserted next to the'outer text 'node containing'inner text'. It has been suggested that Ractive could also deal with merged text nodes, but that would become quite complex because there are certain scenarios where a text node would have to split and be rejoined as the model changed e.g.outer text {{#if foo}}<span>hello</span>{{/if}} the other side. In that case, iffoois initially falsey, the'outer text 'and' the other side'nodes could be merged into a single node. However, iffoobecame truthy, that node would have to be split into two to place on either side of the<span>.Additionally, unescaped HTML mustaches (triples) don't play nicely with enhance because there's no easy way to match up the string content to the target DOM nodes. This may be remedied at some point in the future.
append
Booleanor anchorDefaults to
false. Controls whether existing content is replace and optionally where to place the rendered content.
false- rendered content replaces any existing contents ofel// dom <div id='container'><p>existing content</p></div>// options el: '#container', append: false, //default template: '<p>new content</p>'// result <div id='container'><p>new content</p></div>truerendered content is appended toel// dom <div id='container'><p>existing content</p></div>// options el: '#container', append: true, template: '<p>new content</p>'// result <div id='container'><p>existing content</p><p>new content</p></div>- anchor is any valid option as specified in
elthat resolves to anHTMLElement. Rendered content is appended toelbefore anchor, see ractive.insert()// dom <div id='container'><p>red</p><p>blue</p><p>yellow</p></div>// options el: '#container', append: document.querySelector('p:nth-child(2)'), template: '<p>green</p>'// result <div id='container'><p>red</p><p>green</p><p>blue</p><p>yellow</p></div>
Data & Binding
data
ObjectorFunctionThe data with which to initialise.
// object data: { foo: 'bar' } // function data: function() { return { foo: 'bar' }; }computed
ObjectAn object that maps to a set of computed values.
computed: { area: '${width} * ${height}' }See Computed Properties for more information and examples .
magic
BooleanDefaults to
false. Whether or not to wrap data in ES5 accessors for automatic binding (see magic mode).var data = { foo: 'bar' }; new Ractive({ data: data } ); // will update automagically: data.foo = 'fizz'adapt
ArrayCustom wrappers to be used with all or part of the supplied data, see Adaptors. Unlike components or other registries where there is a template-level directive that informs Ractive that plugin is to be used, adaptors are a data-level construct and so you use the
adaptoption to tell Ractive which adaptors are to be used with that instance. If you define the adaptors directly on the instance or component, you do not need to specify them in theadaptoption.Can either be the adaptor itself, or the name of an adaptor registred via
Ractive.adaptors:Ractive.adaptors.myAdaptor = MyAdaptor1; new Ractive({ adapt: [ 'myAdaptor', MyAdaptor2 ] }adaptors
ObjectA
key: valuehash of adaptors that are specific to this instance. Usually theadaptproperty can directly specify which adaptors to use on this instance and theadaptorsproperty is used to register an adaptor on components orRactive.adaptors.adaptors: { myAdaptor: MyAdaptor }modifyArrays
BooleanDefaults to
false. Whether or not to modify array mutator methods to enable frictionless data binding with lists (see array modification).var items = [ 'red', 'blue' ]; new Ractive({ data: data, modifyArrays: true //default } ); // will update automagically: items.push( 'green' );twoway
BooleanDefaults to
true. Whether or not two-way data binding is enabled (see Two‐way binding).var ractive = new Ractive({ template: '<input value="{{foo}}">', data: { foo: 'bar' }, twoway: false }); // user types "fizz" into <input>, but data value is not changed: console.log( ractive.get( 'foo' ) ); //logs "bar" // updates from the model are still pushed to the view ractive.set( 'foo', 'fizz' ); // input now displays "fizz"Also see static delimiters for one-time binding
lazy
BooleanDefaults to
false. If two-way data binding is enabled, whether to only update data based on text inputs onchangeandblurevents, rather than any event (such as key events) that may result in new data.var ractive = new Ractive({ template: '<input value="{{foo}}">', data: { foo: 'bar' }, lazy: true }); // will not fire as user is typing ractive.on('change', function(){ // only happens on exiting <input> or return if submit console.log('changed!') })isolated
BooleanDefaults to
false. This option is typically only relevant as an extension option for Components. Controls whether the component will look outside itself for data and registry items.
Lifecycle events
See the main entry for lifecycle events.
Transitions & Animations
transitions
ObjectA
key: valuehash of transitions that are specific to this instance. Thekeyis referenced within templates usingintroandoutroattributes on elements, andvalueis a transition functions, see Transitions for more info.template: '<p intro="slide" outro="slide">hello world</p>', transitions: { slide: function ( t, params ) {...} }transitionsEnabled
BooleanDefaults to
true. Whether or not transitions are enabled for this instance.noIntro
BooleanDefaults to
false. Whether or not to skip intro transitions on render.var ractive = new Ractive({ template: '<ul>{{#items}}<li intro="fade">{{.}}</li>{{/items}}</ul>', data: { items: [ 'red', 'blue' ] }, transitions: { fade: function ( t, params ) {...} }, noIntro: true }); // 'red' and 'blue' list items do not fade in on intro ractive.get('items').push( 'green' ); // 'green' list item will fade incomplete
FunctionA function that will be called when render is complete (i.e. all intro transitions have finished). If there are no intro transitions, this function will be called as soon as the instance is created)
template: '<p intro="fade">hello</p>', transitions: { fade: function ( t, params ) {...} }, complete: function () { console.log( '<p> has completed fade in!' ); }easing
ObjectA
key: valuehash of easing function. See Ractive.easinginterpolators
ObjectA
key: valuehash of interpolators use by ractive.animate()
Parsing
csp
BooleanDefaults to
false. Whether or not to add inline functions for expressions after parsing. This can effectively eliminateevalcaused by expressions in templates. It also makes the resulting template no longer JSON compatible, so the template will have to be served viascripttag.delimiters
Arraywhere[ open, close ]Defaults to
[ '{{', '}}' ]. Used to set what delimiters to use when parsing templates.template: 'hello <%= world %>', delimiters: [ '<%=', '%>' ], data: { world: 'earth' } // result: hello earthtripleDelimiters
Arraywhere[ open, close ]Defaults to
[ '{{{', '}}}' ]. Used to set what triple delimiters to use when parsing templates.template: 'hello @html@', tripleDelimiters: [ '@', '@' ], data: { html: '<span>world</span>' } // result: hello <span>world</span>staticDelimiters
Arraywhere[ open, close ]Defaults to
[ '[[', ']]' ]. Used to set what static (one-time binding) delimiters to use when parsing templates.var ractive = new Ractive({ template: 'hello [[foo]]', staticDelimiters: [ '[[', ']]' ], /default data: { foo: 'world' } }); // result: "hello world" ractive.set( 'foo', 'mars' ); // still is: "hello world"staticTripleDelimiters
Arraywhere[ open, close ]Defaults to
[ '[[[', ']]]' ]. Used to set what static (one-time binding) triple delimiters to use when parsing templates.var ractive = new Ractive({ template: 'hello [[[html]]]', staticTripleDelimiters: [ '[[[', ']]]' ], /default data: { html: '<span>world</span>' } }); // result: "hello <span>world</span>" ractive.set( 'html', '<span>mars</span>' ); // still is: "hello world"preserveWhitespace
BooleanDefaults to
false. Whether or not to preserve whitespace in templates when parsing. (Whitespace in<pre>elements is always preserved.)var ractive = new Ractive({ template: '<p>hello\n\n \tworld </p>', preserveWhitespace: false //default }); console.log( ractive.toHTML() ); // "<p>hello world</p>" var ractive = new Ractive({ template: '<p>hello\n\n \tworld </p>', preserveWhitespace: true }); console.log( ractive.toHTML() ); // "<p>hello world </p>"Please note that the browser will still deal with whitespace in the normal fashion.
stripComments
BooleanDefaults to
true. Whether or not to remove comments in templates when parsing.template: '<!-- html comment -->hello world', stripComments: false // result: <!-- html comment -->hello worldsanitize
BooleanorObjectDefaults to
false. Iftrue, certain elements will be stripped from templates at parse time -<applet>,<base>,<basefont>,<body>,<frame>,<frameset>,<head>,<html>,<isindex>,<link>,<meta>,<noframes>,<noscript>,<object>,<param>,<script>,<style>and<title>- as will event attributes (e.g.onclick).template: '<p>some content</p><frame>Am I a bad element or just misunderstood?</frame>', sanitize: true // result: <p>some content</p>Alternatively, pass in an object with an
elementsproperty containing an array of blacklisted elements, and an optionaleventAttributesboolean (truemeans 'disallow event attributes').template: '<p>some content</p><div onclick="doEvil()">the good stuff</div>', sanitize: { elements: [ 'p' ], eventAttributes: true } // result: <div>the good stuff</div>