Skip to content

WebEngine and DomTemplate

Greg Bowler edited this page Apr 18, 2026 · 1 revision

For many PHP.GT applications, this is the page that matters most.

phpgt/dom is a standalone library and can be used anywhere, but in practice a large amount of usage happens inside WebEngine applications.

What WebEngine already does for us

WebEngine provides a pre-constructed HTMLDocument for the current request. That means:

  • the page HTML has already been loaded
  • the document lifecycle is already in motion
  • your page logic can work on the document immediately

So, in WebEngine, we usually do not do this:

$document = new HTMLDocument(file_get_contents("page.html"));

because the framework has already done it.

Manipulating pages using DomTemplate

WebEngine also ships with DomTemplate by default.

That is important because many problems that look like DOM problems are actually template-binding problems:

  • putting scalar values into the page
  • binding object properties
  • repeating lists
  • composing pages from partials and components
  • cleaning up optional elements

When we solve those jobs with direct DOM manipulation, the PHP logic can become tightly coupled to the exact shape of the HTML.

For example:

$document->querySelector(".customer-name")->innerText = $customer->name;
$document->querySelector(".customer-email")->innerText = $customer->email;
$document->querySelector(".customer-status")->innerText = $customer->status;

works, but it means changes to the view structure often force changes in the PHP too.

DomTemplate is designed to reduce that coupling. Read more at https://www.php.gt/domtemplate

A useful division of responsibility

In WebEngine, a practical split is:

  • use DomTemplate for binding application data into the page
  • use DOM directly when we need structural document operations that are genuinely DOM-shaped

Examples where direct DOM is still a good fit:

  • inserting or moving nodes based on parsing or transformation logic
  • sanitising or post-processing imported markup
  • generating fragments from existing nodes
  • working with XML documents or document fragments outside the normal page template flow

Examples where DomTemplate is usually the better fit:

  • filling headings, paragraphs, and form values from data
  • rendering rows, cards, or menu items from lists
  • composing reusable page sections and components

If you are not using WebEngine

Outside WebEngine, phpgt/dom still stands perfectly well on its own. The main difference is that you become responsible for:

  • loading the source HTML
  • constructing the document
  • wiring your own request lifecycle around it

That is completely fine for libraries, scripts, generators, crawlers, email renderers, or bespoke applications.


The final page covers the behaviour that is closest to "know this before it catches you out": Specification notes and quirks.

Clone this wiki locally