becklyn/html-builder
Lightweight PHP HTML builder for composing elements and attribute strings. Create HtmlElement nodes, render with escaping by default, support boolean/null/false attribute rules, and inject trusted raw HTML via SafeMarkup when needed.
Installation:
composer require becklyn/html-builder
No configuration required—just autoload via Composer.
First Use Case: Generate a basic HTML string:
use Becklyn\HtmlBuilder\Html;
$html = Html::tag('div', 'Hello, World!');
echo $html; // Outputs: <div>Hello, World!</div>
Key Entry Points:
Html::tag() – Core method for creating HTML elements.Html::attr() – Helper for attributes (e.g., Html::attr('class', 'btn')).Html::raw() – Escape HTML safely (e.g., Html::raw('<b>bold</b>')).Dynamic Element Creation:
$user = User::find(1);
$avatar = Html::tag('img', '', [
'src' => $user->avatar_url,
'alt' => $user->name,
'class' => 'avatar',
]);
Nested Structures:
$card = Html::tag('div', [
Html::tag('h3', 'Title'),
Html::tag('p', 'Content'),
], ['class' => 'card']);
Reusable Components:
function button(string $text, array $attrs = []): string {
return Html::tag('button', $text, $attrs);
}
// Usage: button('Submit', ['class' => 'btn-primary'])
Integration with Blade:
@php
$alert = Html::tag('div', 'Warning!', ['class' => 'alert']);
@endphp
{!! $alert !!}
Html::attr() for dynamic attributes (e.g., in loops):
$items = collect([1, 2, 3]);
$list = $items->map(fn($id) => Html::tag('li', '', [
'data-id' => $id,
]))->implode('');
XSS Risks:
Html::tag() escapes content by default. Use Html::raw() only for trusted HTML.Html::raw() (e.g., with Str::of()->markdown()).Attribute Quoting:
class="btn btn--primary") may break.Html::attr() for dynamic attributes or manually escape:
Html::tag('div', '', ['class' => 'btn btn--"primary"']);
Self-Closing Tags:
<img /> vs <img> syntax may cause rendering issues.Html::tag('img', '', [], true) (if supported).dd($html) to verify generated markup.Html::tag() trims content by default. Use Html::raw() for pre-formatted strings.Custom Tag Helpers:
Html::macro('link', function(string $text, string $url, array $attrs = []) {
return Html::tag('a', $text, array_merge($attrs, ['href' => $url]));
});
// Usage: Html::link('Click', '/home')
Override Default Behavior:
Modify the Html facade binding in AppServiceProvider:
Html::macro('customTag', function() { ... });
Integration with Laravel Collectives:
Combine with HTML facade for Blade compatibility:
use Collective\Html\Html as CollectiveHtml;
CollectiveHtml::macro('becklynTag', function($tag, $content = null) {
return app(\Becklyn\HtmlBuilder\Html::class)->tag($tag, $content);
});
How can I help you explore Laravel packages today?