21torr/html-builder
Fluent HTML builder for Laravel/PHP. Programmatically compose tags, attributes, and nested elements with a clean API to generate consistent markup without mixing large HTML strings into your views or controllers.
Pros:
getParentElement() method improves HTML structure manipulation, enabling more complex nested component hierarchies (e.g., dynamically styled parent-child relationships in tables or accordions).@component directives to create reusable, stateful HTML blocks (e.g., modals with parent context).Cons:
PHP/Laravel Compatibility:
@php blocks or custom Blade components to manipulate parent elements:
@php
$builder = app(HtmlBuilder::class);
$parent = $builder->div()->getParentElement();
$parent->addClass('container');
@endphp
$this->app->bind(HtmlBuilder::class, function () {
return (new HtmlBuilder())->setParentContext($parentElement);
});
Testing & Validation:
$builder = new HtmlBuilder();
$parent = $builder->div()->id('parent');
$child = $builder->span()->appendTo($parent);
$this->assertEquals('parent', $child->getParentElement()->id());
Key Risks:
getParentElement() enforce ARIA roles or semantic HTML for parent-child relationships? Manual validation may be needed.@stack/@push may suffice for parent-child relationships in layouts.Mitigation:
class LaravelHtmlBuilder extends HtmlBuilder {
public function safeAppendTo(Element $parent, string $content) {
// Validate parent before appending
}
}
roles)?Best Fit:
wire:click="$parent->toggle()").parent->addClass('bg-gray-100')).Poor Fit:
Pilot Phase:
getParentElement() to style parent rows dynamically:
@php
$builder = app(HtmlBuilder::class);
$table = $builder->table();
$row = $builder->tr()->addClass('hover:bg-gray-50');
$row->getParentElement()->addClass('striped');
@endphp
Incremental Adoption:
parent classes) with builder methods.DashboardBuilder extends HtmlBuilder).// resources/views/components/table.blade.php
<x-table :rows="$builder->buildRows($data)" />
Tooling Integration:
[...] for dynamic IDs).$this->assertSame($parent, $child->getParentElement());
$this->assertEquals('expected-class', $parent->getAttribute('class'));
Laravel-Specific Considerations:
$this->app->singleton(HtmlBuilder::class, function () {
return (new HtmlBuilder())->setDefaultParent(
$this->app->make('view')->make('layouts.partials.container')
);
});
Blade::directive('parent', function ($expression) {
return "<?php echo app(HtmlBuilder::class)->{$expression}->getParentElement(); ?>";
});
Usage: @parent('div()->addClass("container")')PHP Version:
addClass(string $class)) are recommended for clarity.Dependency Conflicts:
dom or php-dom extensions.Str::of() or htmlspecialchars().| Phase | Task | Dependencies | |---------------------|
How can I help you explore Laravel packages today?