Templates aus Text, Dateien und URLs mit TEMPLATE rendern
TEMPLATE(source, model, [$]) rendert ein Tangular-Template und gibt ein Promise mit dem Text zurück. Die source kann sein:
- ein Text, der
{{ ... }}enthält: er ist das Template selbst - der Name einer Datei im Ordner
templates:TEMPLATE('invoice', model)liesttemplates/invoice.html(ein~am Anfang macht den Namen zu einem absoluten Pfad) - eine
http://- oderhttps://-Adresse, die der Quellcode vontotal5herunterlädt (auf dieser Seite nicht geprüft)
Ta ist ein anderer Name für Tangular. Anders als bei Tangular.render() steht das Modell als value zur Verfügung: Schreibe {{ value.name }}. Eine Template-Datei kann außerdem zwei Blöcke enthalten, die TEMPLATE liest und aus der Ausgabe entfernt: ein <script>, das Thelpers Helper hinzufügt, und ein <script type="text/json"> mit dem Standardmodell, das verwendet wird, wenn kein Modell übergeben wird.
<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>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'));
}