# Renderizza template da testo, file e URL con TEMPLATE

> Usa TEMPLATE() per renderizzare un template Tangular che è un testo, un file della cartella dei template o un URL, con i propri helper e un modello predefinito.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 078919c8f01945f01f4b5d6c6c474da520b712afabdecc7e8ef626f48ea2482a
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`TEMPLATE(source, model, [$])` renderizza un template Tangular e restituisce una **promise** con il testo. La `source` può essere:

- un testo che contiene `{{ ... }}`: è il template stesso
- il nome di un file della cartella `templates`: `TEMPLATE('invoice', model)` legge `templates/invoice.html` (una `~` all'inizio rende il nome un percorso assoluto)
- un indirizzo `http://` o `https://`, che il sorgente di `total5` scarica (non verificato in questa pagina)

`Ta` è un altro nome di `Tangular`. A differenza di `Tangular.render()`, il modello è disponibile come **`value`**: scrivi `{{ value.name }}`. Un file di template può anche contenere due blocchi che `TEMPLATE` legge e rimuove dall'output: un `<script>` che aggiunge helper a `Thelpers` e un `<script type="text/json">` con il modello predefinito, usato quando non viene passato alcun modello.

```html templates/invoice.html
<script>
	Thelpers.money = function(value) {
		return (value || 0).toFixed(2) + ' EUR';
	};
</script>
<script type="text/json">{ "customer": "Anonymous", "total": 0 }</script>
<h1>Invoice for {{ value.customer }}</h1>
<p>Total: {{ value.total | money() }}</p>
```

```js controllers/documents.js
exports.install = function() {
	ROUTE('GET /text/', text);
	ROUTE('GET /file/', file);
	ROUTE('GET /default/', withdefault);
	ROUTE('GET /absolute/', absolute);
	ROUTE('GET /alias/', alias);
};

async function text($) {
	$.plain(await TEMPLATE('Hello {{ value.name }}!', { name: $.query.name || 'world' }));
}

async function file($) {
	$.plain(await TEMPLATE('invoice', { customer: 'Ana', total: 12.5 }));
}

function alias($) {
	$.json({ same: Ta === Tangular, rendered: Ta.render('{{ name }}', { name: 'x' }) });
}

async function absolute($) {
	const file = require('path').join(__dirname, '..', 'templates', 'invoice.html');
	$.plain(await TEMPLATE('~' + file, { customer: 'Eva', total: 1 }));
}

async function withdefault($) {
	$.plain(await TEMPLATE('invoice'));
}
```
