ForgeTotal.js 5
de

Total.js 5

Templates aus Text, Dateien und URLs mit TEMPLATE rendern

Total.js 5 · total5@0.0.19 templatescontenttangular Mit Total.js 5 ausgeführt

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) liest templates/invoice.html (ein ~ am Anfang macht den Namen zu einem absoluten Pfad)
  • eine http://- oder https://-Adresse, die der Quellcode von total5 herunterlä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.

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>
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'));
}