Template Binding
Polymer’s TemplateBinding library extends the capabilities of the HTML Template Element by enabling it to create, manage, and remove instances of content bound to data defined in JavaScript. Although internal in Polymer, it is also useful standalone.
Learn the tech
Template Binding extends the <template>
element with new attributes for binding data:
bind
repeat
if
ref
Basic usage
bind
<template bind="{{ singleton }}">
Creates a single instance with {{ bindings }} when singleton model data is provided.
</template>
repeat
<template repeat="{{ collection }}">
Creates an instance with {{ bindings }} for every element in the array collection.
</template>
Named scopes:
<template repeat="{{ user in users }}">
{{user.name}}
</template>
Indexing:
<template repeat="{{ foo, i in foos }}">
<template repeat="{{ value, j in foo }}">
{{ i }}:{{ j }}. {{ value }}
</template>
</template>
if
<template bind if="{{ conditionalValue }}">
Binds if and only if conditionalValue is truthy.
</template>
<template if="{{ conditionalValue }}">
Binds if and only if conditionalValue is truthy. (same as *bind if*)
</template>
<template repeat if="{{ conditionalValue }}">
Repeat if and only if conditionalValue is truthy.
</template>
ref
<template id="myTemplate">
Used by any template which refers to this one by the ref attribute
</template>
<template bind ref="myTemplate">
When creating an instance, the content of this template will be ignored,
and the content of #myTemplate is used instead.
</template>
Activating a template
Setting data model on the template causes any bind
, repeat
or if
attribute
directive to begin acting:
document.querySelector('template').model = {...};
Unbinding a model
Node.unbind(<property>)
can be used to unbind a property. For example, to unbind
a model set using the bind
attribute, call template.unbind('bind')
:
<button onclick="removeGo()">test</button>
<template id="greeting" bind="{{ salutations }}">
Hello, {{who}} - {{what}}
</template>
<script>
var t = document.querySelector('#greeting');
var model = {
salutations: { what: 'GoodBye', who: 'Imperative' }
};
t.model = model;
function removeGo() {
t.unbind('bind');
}
</script>
Examples
Please refer to the HowTo examples.