Built on top of PHP.Gt/Dom, this project provides simple view templating and dynamic data binding.
Directly manipulating the DOM in your code can lead to tightly coupling the logic and view. Binding data using custom elements and data attributes leads to highly readable, maintainable view files that are loosely coupled to the application logic.
Consider a page with an unordered list (<ul>
). Within the list there should be a list item (<li>
) for every element of an array of data.
In this example, we will simply use an array to contain the data, but the data can come from a data source such as a database.
<!doctype html>
<h1>Shopping list</h1>
<shopping-list></shopping-list>
<p>The use of a custom element is more useful on more complex pages, but is shown here as an example.</p>
<ul id="shopping-list">
<li data-template data-bind:text="title">Item name</li>
</ul>
<?php
require "vendor/autoload.php";
$html = file_get_contents("example.html");
$document = new \Gt\DomTemplate\HTMLDocument($html, "./_template");
$document->prepareTemplates();
$data = [
["id" => 1, "title" => "Tomatoes"],
["id" => 2, "title" => "Noodles"],
["id" => 3, "title" => "Cheese"],
["id" => 4, "title" => "Broccoli"],
];
$outputTo = $document->getElementById("shopping-list");
$outputTo->bind($data);
<!doctype html>
<h1>Shopping list</h1>
<ul id="shopping-list">
<li>Tomatoes</li>
<li>Noodles</li>
<li>Choose</li>
<li>Broccoli</li>
</ul>