ForgeTotal.js 5
nl

Total.js 5

Render templates uit tekst, bestanden en URL's met TEMPLATE

Total.js 5 · total5@0.0.19 templatescontenttangular Uitgevoerd met Total.js 5

TEMPLATE(source, model, [$]) rendert een Tangular-template en geeft een promise met de tekst terug. De source kan zijn:

  • een tekst die {{ ... }} bevat: dat is de template zelf
  • de naam van een bestand in de map templates: TEMPLATE('invoice', model) leest templates/invoice.html (een ~ aan het begin maakt van de naam een absoluut pad)
  • een http://- of https://-adres, dat de broncode van total5 downloadt (op deze pagina niet gecontroleerd)

Ta is een andere naam voor Tangular. Anders dan bij Tangular.render() is het model beschikbaar als value: schrijf {{ value.name }}. Een templatebestand kan ook twee blokken bevatten die TEMPLATE leest en uit de uitvoer verwijdert: een <script> dat helpers aan Thelpers toevoegt en een <script type="text/json"> met het standaardmodel, dat wordt gebruikt als er geen model wordt doorgegeven.

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