Templates with Tangular
Render HTML from data with the Tangular template engine that ships with jComponent.
On this page
Tangular is the template engine included in jComponent. It turns a template and a model into a string of HTML. The global objects are Tangular (also available as Ta) and Thelpers.
Rendering a template
Tangular.render(template, [model], [repository], [helpers]) compiles a template and runs it at once:
var model = { name: 'Peter <b>', address: { city: 'Bratislava' } };
Tangular.render('Hello {{ name }}, {{ address.city }}, {{ phone.number }}!', model);
// Hello Peter <b>, Bratislava, !Three rules show up in this example:
- A value is written between
{{and}}. - Output is HTML-encoded.
- A missing value renders as nothing, even in a nested path such as
phone.number.
Values and expressions
A command can be a JavaScript expression. {{ }} writes the model itself, and the raw helper turns off encoding:
Tangular.render('{{ price * 2 }} {{ name.length }} {{ a || b }}', { price: 5, name: 'abc', a: 0, b: 'x' });
// 10 3 x
Tangular.render('{{ }}', 'The model itself');
// The model itself
Tangular.render('{{ name | raw }}', { name: '<b>Peter</b>' });
// <b>Peter</b>Use raw only with content you trust.
Conditions
{{ if }} starts a condition and {{ fi }} ends it. {{ else if }} and {{ else }} are optional:
var template = '{{ if stock > 5 }}In stock{{ else if stock > 0 }}Almost gone{{ else }}Sold out{{ fi }}';
Tangular.render(template, { stock: 10 }); // In stock
Tangular.render(template, { stock: 2 }); // Almost gone
Tangular.render(template, { stock: 0 }); // Sold outLoops
{{ foreach item in list }} repeats the content up to {{ end }}. $index is the position of the current item:
var model = { users: [{ name: 'Peter' }, { name: 'Lucia' }] };
Tangular.render('{{ foreach user in users }}{{ $index }}: {{ user.name }}, {{ end }}', model);
// 0: Peter, 1: Lucia,A loop over an object gets items with the properties key and value:
var model = { settings: { theme: 'dark', size: 12 } };
Tangular.render('{{ foreach item in settings }}{{ item.key }}={{ item.value }};{{ end }}', model);
// theme=dark;size=12;{{ continue }} skips to the next item and {{ break }} ends the loop:
var template = '{{ foreach id in ids }}{{ if id === 2 }}{{ continue }}{{ fi }}{{ if id === 4 }}{{ break }}{{ fi }}{{ id }} {{ end }}';
Tangular.render(template, { ids: [1, 2, 3, 4] });
// 1 3An empty or missing list renders nothing. In nested loops, $index holds the position of the innermost loop that ran last, so an outer loop that reads $index after an inner loop gets the inner value:
var template = '{{ foreach row in rows }}[{{ $index }}:{{ foreach cell in row.cells }}{{ $index }}{{ cell }} {{ end }}{{ $index }}]{{ end }}';
Tangular.render(template, { rows: [{ cells: ['a', 'b'] }, { cells: ['c'] }] });
// [0:0a 1b 1][1:0c 0]Helpers
A helper transforms a value. Write it after a | character. Helpers can take arguments and can be chained:
Tangular.render("{{ count | pluralize('no items', '# item', '# items', '# items') }}", { count: 3 });
// 3 items
Tangular.render('{{ price | format(2) }}', { price: 1234.5 });
// 1 234.50
Tangular.render("{{ note | def('none') }}", { note: '' });
// none
Tangular.render("{{ data | encode('json') }} {{ q | encode('url') }}", { data: { a: 1 }, q: 'a b&c' });
// {"a":1} a%20b%26cThe included helpers are described in the Tangular helpers reference.
Encoding with helpers
A command that uses a helper is not encoded automatically. Add the encode helper at the end when the value can contain HTML:
var helpers = {
upper: function(value) {
return value.toUpperCase();
}
};
Tangular.render('{{ name | upper }}', { name: '<i>peter</i>' }, null, helpers);
// <I>PETER</I>
Tangular.render('{{ name | upper | encode }}', { name: '<i>peter</i>' }, null, helpers);
// <I>PETER</I>Writing a helper
Tangular.register(name, fn) adds a helper for all templates. The function receives the value followed by the arguments from the template, and this is the model:
Tangular.register('stars', function(value) {
return '*'.padLeft(value, '*');
});
Tangular.render('{{ rating | stars }}', { rating: 3 });
// ***To use a helper in one template only, pass an object with helpers as the fourth argument of Tangular.render(). A name that matches no helper writes a warning to the console and returns the value unchanged.
Compiling a template
Tangular.compile(template) returns a function. Compile once and call the function as often as you need, with the model, the repository and the helpers as arguments:
var row = Tangular.compile('<li>{{ name }} ({{ $.currency }})</li>');
row({ name: 'Keyboard' }, { currency: 'EUR' }); // <li>Keyboard (EUR)</li>
row({ name: 'Mouse' }, { currency: 'USD' }); // <li>Mouse (USD)</li>Strings also have a shortcut:
'Hello {{ name }}'.render({ name: 'Peter' }); // Hello PeterIf a template fails while it runs, Tangular writes the error to the console and the result is undefined.
The repository
The repository is a second object that is available as $ in the template. Use it for data that does not belong to the model:
Tangular.render('{{ foreach item in $.items }}{{ item }} {{ end }}', {}, { items: [1, 2] });
// 1 2Custom delimiters
Tangular.compile() accepts different delimiters as its second and third arguments. They are parts of a regular expression, so escape special characters:
var custom = Tangular.compile('Hello [[ name ]]', '\\[\\[', '\\]\\]');
custom({ name: 'Lucia' }); // Hello LuciaTemplates in bindings
The template command of <ui-bind> renders a template with the value of the path and renders it again on every change. Inside the template, the value is available as value:
<script>
var user = { name: 'Peter', roles: ['admin', 'editor'] };
</script>
<ui-bind path="user" config="template">
<script type="text/html">
<b>{{ value.name }}</b>
{{ foreach role in value.roles }}<span>{{ role }}</span>{{ end }}
</script>
</ui-bind>See Data binding and the ui-bind reference.
Templates in components
A component usually compiles its template once in make and calls it in setter:
COMPONENT('userlist', function(self) {
var template;
self.make = function() {
template = Tangular.compile('<ul>{{ foreach user in value }}<li>{{ user }}</li>{{ end }}</ul>');
};
self.setter = function(value) {
self.html(template({ value: value }));
};
});With names = ['Peter', 'Lucia'] and ui-component name="userlist" path="names", the component renders ulliPeter/liliLucia/li/ul. See Creating components.