Skip to content
Greg Bowler edited this page Sep 1, 2018 · 28 revisions

The DOM template repository is separately maintained at https://github.com/PhpGt/DomTemplate

A core concept when developing WebEngine applications is the use of the Document Object Model (DOM). WebEngine exposes the page's DOM to your code as described in DOM manipulation. The DOM implementation aims to be as standards compliant as possible, matching the APIs you'd expect to see in client side code.

However, directly manipulating the DOM in your code can lead to tightly coupling the logic and view. As a powerful solution, binding data using custom elements and data attributes leads to highly readable, maintainable view files that are loosely coupled to the application logic.

HTML templates

The concept of HTML templates introduces special elements that are extracted from the DOM before the page is rendered, and supplied to your PHP code, allowing you to clone the template elements multiple times across the page. This is useful for building up lists of repeating content, or for hiding/displaying content depending on certain circumstances.

Templates that are added to the page are given a class prefix of .t- followed by their template name.

There are multiple methods of using templates within WebEngine, as described below.

The data-template attribute

The simplest way to extract an element as a template is to add the data-template attribute to the element. Elements with this attribute are extracted out of the DOM before the page is rendered and are stored in the DOM's template list for easy referencing in PHP.

The value of the data-template attribute is the name of the template. In PHP you can obtain a clone of the template element by its template name. As the element is extracted from the DOM, it will retain a reference of its original parent, allowing you to insert the template back in-place with the insertTemplate() function.

Example:

<h1>Shopping list:</h1>

<ul>
	<li data-template="product">Product name</li>
</ul>
public function outputShoppingList() {
	$li = $this->document->getTemplate("product");
	$li->innerText = "Coffee";
	$li->insertTemplate();
}

Using components as templates

When template elements are extracted from the DOM, they can be referenced by their name using the getTemplate function of the HTMLDocument. Custom components can also be referenced by name using the same method, treating a component as a template.

For example:

$mainMenuTemplate = $this->document->getTemplate("main-menu");

Components that are added to the page as a template will receive both the the c- and t- class prefixes, indicating that they were added as a template.

Clone this wiki locally