Rendering HTML
Domovoy provides two renderer implementations: HtmlRenderer
for full-string
output and HtmlStreamingRenderer
for generator-based streaming.
HtmlRenderer
The default renderer produces a complete HTML string:
use Domovoy\VirtualDom\Renderer\HtmlRenderer;
$renderer = new HtmlRenderer();
echo $renderer->render($node);
// <div id="main"><p>Hello</p></div>
Pretty-Print
Pass an indentation string to enable pretty-printed output:
$renderer = new HtmlRenderer(indentation: ' ');
echo $renderer->render($node);
// <div id="main">
// <p>Hello</p>
// </div>
Tab indentation works too:
$renderer = new HtmlRenderer(indentation: "\t");
Single text children are kept inline (no extra newline):
// <p>Hello</p> — not wrapped onto its own line
HtmlStreamingRenderer
For large documents or chunked HTTP responses, use the streaming renderer. It yields HTML fragments via a Generator:
use Domovoy\VirtualDom\Renderer\HtmlStreamingRenderer;
$renderer = new HtmlStreamingRenderer();
foreach ($renderer->render($node) as $chunk) {
echo $chunk;
flush();
}
Each yield
produces a piece of the final HTML, so output can begin before
the full tree is traversed.
XSS Protection
All text content is escaped with htmlspecialchars()
using
ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5
. This covers:
- Attribute values:
<div class="safe & sound"> - Text nodes:
<p><script>alert(1)</script></p>
The only way to bypass escaping is via raw()
, which is an explicit opt-in.
There is no accidental path to unescaped output.
Attribute Rendering
The renderer handles several attribute patterns automatically:
- Boolean attributes
:
truerenders the attribute name alone (disabled),falseomits it entirely. - Null attributes : omitted from output.
- IDL-to-HTML mapping
:
classNamerenders asclass,htmlForrenders asfor, etc. Mapping is defined by#[HtmlName]PHP attributes on generated classes. - Data attributes
:
DataAttributesrenders asdata-*key-value pairs. - Nested attributes
: Global attributes (ARIA, event handlers) are rendered
from nested objects marked with
#[NestedAttributes].