---
title: Templates with Tangular
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/tangular/
updated: 2026-11-18T13:55:34.124Z
---

# Templates with Tangular

> How to write templates with Tangular: values, conditions, loops and helpers.

Tangular is the template engine included in the library. It turns a template and a data object into an HTML string. Templates are compiled to JavaScript functions, so one template can render many times.

## Rendering a template

`Tangular.render(template, [model], [repository], [helpers])` compiles and renders in one step. `Tangular.compile(template)` returns a function to use repeatedly.

```js
var html = Tangular.render('<h1>{{ title }}</h1><p>{{ user.name }}</p>', { title: 'Team', user: { name: 'Ann' } });
console.log(html);

var template = Tangular.compile('Hello {{ name }}!');
console.log(template({ name: 'Ann' }));
console.log(template({ name: 'Bob' }));
```

```text
<h1>Team</h1><p>Ann</p>
Hello Ann!
Hello Bob!
```

A compiled template is called as `template(model, [repository], [helpers])`. `Ta` is a short alias of `Tangular`.

## Values

`{{ name }}` prints a value of the model. The output is HTML-encoded. The `raw` helper prints the value as it is, so use it only for HTML you trust.

```js
var model = { name: '<b>Ann</b>', age: 30, user: { address: null }, score: 0, note: null };

Tangular.render('{{ name }}', model);                       // &lt;b&gt;Ann&lt;/b&gt;
Tangular.render('{{ name | raw }}', model);                 // <b>Ann</b>
Tangular.render('[{{ user.address.city }}]', model);        // []
Tangular.render('{{ score }}|{{ note }}|{{ age + 1 }}|{{ name.length }}', model); // 0||31|10
Tangular.render('{{ age > 18 ? "adult" : "minor" }}', model); // adult
```

A missing value prints nothing, and so does `null`. The number `0` is printed. A tag can hold a JavaScript expression over the values of the model.

## Conditions

A condition starts with `{{ if }}` and ends with `{{ fi }}`. `{{ else if }}` and `{{ else }}` are optional.

```js
var template = Tangular.compile('{{ if age >= 65 }}senior{{ else if age >= 18 }}adult{{ else }}child{{ fi }}');

template({ age: 70 }); // senior
template({ age: 30 }); // adult
template({ age: 12 }); // child
```

A condition is plain JavaScript. Reading a property of a missing object is an error there, which is written to the console and leaves the result `undefined`. Check the object first:

```js
Tangular.render('{{ if user && user.active }}on{{ else }}off{{ fi }}', {}); // off
```

## Loops

`{{ foreach item in list }}` repeats its content until `{{ end }}`. `$index` holds the position of the current item.

```js
var model = {
  tags: ['red', 'green', 'blue'],
  sizes: { s: 10, m: 20 },
  groups: [{ name: 'A', items: [1, 2] }, { name: 'B', items: [3] }]
};

Tangular.render('{{ foreach tag in tags }}{{ $index }}:{{ tag }} {{ end }}', model);
// 0:red 1:green 2:blue

Tangular.render('{{ foreach m in sizes }}{{ m.key }}={{ m.value }} {{ end }}', model);
// s=10 m=20

Tangular.render('{{ foreach g in groups }}{{ g.name }}({{ foreach n in g.items }}{{ n }}{{ end }}) {{ end }}', model);
// A(12) B(3)
```

An object is looped as a list of items with `key` and `value`. A missing or empty list renders nothing.

`{{ continue }}` skips to the next item and `{{ break }}` ends the loop:

```js
Tangular.render('{{ foreach tag in tags }}{{ if $index === 1 }}{{ continue }}{{ fi }}{{ tag }} {{ end }}', model);
// red blue

Tangular.render('{{ foreach tag in tags }}{{ if $index === 2 }}{{ break }}{{ fi }}{{ tag }} {{ end }}', model);
// red green
```

Nested loops share one `$index`. After an inner loop finishes, `$index` keeps the last position of that inner loop until the outer loop moves on, so read the outer position ahead of the inner loop:

```js
var model = { groups: [{ items: ['a', 'b', 'c'] }, { items: ['d'] }] };

Tangular.render('{{ foreach g in groups }}{{ $index }}:{{ foreach n in g.items }}{{ n }}{{ end }}:{{ $index }} {{ end }}', model);
// 0:abc:2 1:d:0
```

## Helpers

A helper transforms a value. It follows the value after a `|`, and helpers can be chained.

| Helper | Description |
| --- | --- |
| `raw` | Prints the value without encoding. |
| `encode([type])` | Encodes for HTML. The types `url`, `json`, `json2` and `querify` select another output. |
| `format(...)` | Formats a number or a date. |
| `pluralize(zero, one, few, other)` | Selects a text by a number. |
| `empty([text])`, `def([text])` | Prints `text` or `DEF.empty` for an empty value. |
| `currency([name])` | Formats a number with a currency from `DEF.currencies`. |
| `cl(name, [key])` | Finds a label in the code list `DEF.cl[name]` by `id`. |

The arguments of each helper are described in [Tangular helpers](../../reference/tangular-helpers/).

```js
DEF.currencies.eur = function(value) {
  return value.format(2) + ' EUR';
};
DEF.cl.status = [{ id: 1, name: 'Open' }, { id: 2, name: 'Closed' }];

var model = {
  price: 1234.5,
  created: new Date(2026, 0, 15, 10, 5),
  count: 3,
  note: '',
  status: 2,
  query: 'a b&c',
  data: { a: 1 }
};
```

| Template | Output |
| --- | --- |
| `{{ price \| format(2) }}` | `1 234.50` |
| `{{ created \| format("yyyy-MM-dd HH:mm") }}` | `2026-01-15 10:05` |
| `{{ count \| pluralize("no items", "# item", "# items", "# items") }}` | `3 items` |
| `{{ note \| empty }}` | `---` |
| `{{ note \| empty("n/a") }}` | `n/a` |
| `{{ price \| currency("eur") }}` | `1 234.50 EUR` |
| `{{ status \| cl("status") }}` | `Closed` |
| `{{ query \| encode("url") }}` | `a%20b%26c` |
| `{{ data \| encode("json") }}` | `{"a":1}` |

## Custom helpers

`Tangular.register(name, callback)` adds a helper for all templates. The first argument of the callback is the value, the next ones come from the template, and `this` is the model.

```js
Tangular.register('initials', function(value) {
  return value.split(' ').map(function(word) {
    return word.charAt(0);
  }).join('');
});

Tangular.register('wrap', function(value, before, after) {
  return before + value + after;
});

Tangular.register('fullname', function(value) {
  return this.first + ' ' + value;
});

var model = { name: 'Ann Lee', first: 'Ann', last: 'Lee', html: '<i>' };

Tangular.render('{{ name | initials }}', model);             // AL
Tangular.render('{{ name | initials | wrap("[", "]") }}', model); // [AL]
Tangular.render('{{ last | fullname }}', model);             // Ann Lee
```

The output of a helper is not encoded. Add `encode` at the end of the chain when the value comes from a user:

```js
Tangular.render('{{ html | wrap("", "") }}', model);          // <i>
Tangular.render('{{ html | wrap("", "") | encode }}', model); // &lt;i&gt;
```

Helpers for one call only go to the last argument of `render()`:

```js
var helpers = { shout: function(value) { return value + '!'; } };
Tangular.render('{{ first | shout }}', model, null, helpers); // Ann!
```

## The repository

The repository is a second object for values that do not belong to the model. Templates read it through `$`:

```js
var repository = { title: 'Users', limit: 2 };

Tangular.render('{{ $.title }}: {{ name }}', { name: 'Ann' }, repository);
// Users: Ann

var template = Tangular.compile('{{ foreach n in items }}{{ if $index < $.limit }}{{ n }} {{ fi }}{{ end }}');
template({ items: ['a', 'b', 'c'] }, repository);
// a b
```

## Custom delimiters

`Tangular.compile(template, begin, end)` replaces `{{` and `}}`. Both values are parts of a regular expression, so special characters need escaping:

```js
var template = Tangular.compile('[[ name ]] and {{ other }}', '\\[\\[', '\\]\\]');
template({ name: 'Ann' }); // Ann and {{ other }}
```

## Line breaks

A line break directly in front of a tag and at the end of the template is removed:

```js
Tangular.render('a\n{{ name }}\nb\n', { name: 'X' }); // "aX\nb"
```

## Templates in the page

The `template` command of `<ui-bind>` renders a Tangular template with the value of a path. Inside the template, the value is available as `value`, and the template renders again when the value changes.

```html
<ui-bind path="team" config="template">
  <script type="text/html">
    <ul>{{ foreach m in value.people }}<li>{{ m.name }}</li>{{ end }}</ul>
  </script>
</ui-bind>

<script>
SET('team', { people: [{ name: 'Ann' }, { name: 'Bob' }] });
</script>
```

The element renders `<ul><li>Ann</li><li>Bob</li></ul>`. More about bindings is in [Data binding](../data-binding/).
