ForgeTotal.js 5
en

Total.js 5

Render templates from text, files and URLs with TEMPLATE

Total.js 5 · total5@0.0.19 templatescontenttangular Executed against Total.js 5

TEMPLATE(source, model, [$]) renders a Tangular template and returns a promise with the text. The source can be:

  • a text that contains {{ ... }}: it is the template itself
  • the name of a file of the templates folder: TEMPLATE('invoice', model) reads templates/invoice.html (a ~ at the start makes the name an absolute path)
  • an http:// or https:// address, which the source of total5 downloads (not checked on this page)

Ta is another name of Tangular. Unlike Tangular.render(), the model is available as value: write {{ value.name }}. A template file can also carry two blocks that TEMPLATE reads and removes from the output: a <script> that adds helpers to Thelpers and a <script type="text/json"> with the default model, which is used when no model is passed.

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