becklyn/html-builder

Simple helpers for building HTML

2.2.1 2022-02-17 11:28 UTC

This package is auto-updated.

Last update: 2024-10-17 17:30:55 UTC


README

Elements Builder

use Becklyn\HtmlBuilder\Builder\HtmlBuilder;
use Becklyn\HtmlBuilder\Node\HtmlElement;

$builder = new HtmlBuilder();

$link = new HtmlElement("a", [
    "href" => "https://becklyn.com", 
], [
    "Becklyn Studios"
]);

assert('<a href="https://becklyn.com">Becklyn Studios</a>' === $builder->buildElement($link));

Attributes Builder

use Becklyn\HtmlBuilder\Builder\HtmlBuilder;
use Becklyn\HtmlBuilder\Node\HtmlAttributes;

$builder = new HtmlBuilder();

$attributes = $builder->buildAttributes(new HtmlAttributes([
    "href" => "https://becklyn.com",
    "target" => "_blank",
]));

echo "<a {$attributes}>Becklyn</a>"; 

Special values:

  • false: entry will be omitted
  • null: will be omitted
  • true: will be rendered as boolean attribute, eg. "checked" => true as <input checked>.
$full = $builder->build([
    "first" => "a",
    "removed1" => false,
    "removed2" => null,
    "checked" => true,
    "last" => "b",
]);


assert($full === 'first="a" checked last="b"'); // true

Adding pre-compiled HTML to an element

To avoid automatic escaping of the content, you can use SafeMarkup:

$link = new HtmlElement("div");
$link->addContent(new SafeMarkup("This will <b>not</b> be escaped!"));

assert('<div>This will <b>not</b> be escaped!</div>' === $builder->buildElement($link));