Skip to content

Template Functions

Pre-release
Pre-release
Compare
Choose a tag to compare
@CMEONE CMEONE released this 13 Mar 01:18
· 19 commits to main since this release

In this release, we added a powerful new feature: template functions. By defining functions in the renderTemplate options, you can call these functions within your template. Here is an example of displaying a list from an array:

tApp.renderTemplate("./views/template.html", {
	list: ["First element", "Second element", "Third element"],
	loop: function(elements) {
		let returnStr = "";
		for(let i = 0; i < elements.length; i++) {
			returnStr += `<li>${elements[i]}</li>\n`;
		}
		return returnStr;
	}
});

The loop function defined in the options loops through all elements inputted and adds an li tag to the end of the return string with the value of the element, then returns the HTML.

To call this function in the template:

<ul>
	{{{ loop(list); }}}
</ul>

It's that simple! You can create any custom functions to embed into your templates for code reusability, for example, custom elements (using functions and parameters in place of HTML tags to render complex and reusable element structures). We will also be adding for and while loops in a later release (in place of this looping function method).

Additionally, we added some more features to templates. To have a comment, surround the comment in {# #}, and it will not be rendered to the DOM (not even as an HTML comment):

{# Comments #}

Finally, with code execution ({{{ }}}), we do not render values to the DOM which return null or undefined, but some operations such as setting variables return the current value of the variable, which you might not want rendered to the DOM. Instead of appending null or undefined to the end of the expression to return null and undefined (which tApp does not render to the DOM), you can use {{{@ }}}:

{{{@ i = 0; }}}

There were a ton of new templating features in this release, but more are on the way!