Skip to content

Instantly share code, notes, and snippets.

@elazar
Last active November 13, 2022 01:11
Show Gist options
  • Save elazar/2d6f23c5384f60e32f0ff024a330c145 to your computer and use it in GitHub Desktop.
Save elazar/2d6f23c5384f60e32f0ff024a330c145 to your computer and use it in GitHub Desktop.
HTML-in-PHP
<?php
if (!function_exists('array_is_list')) {
function array_is_list(array $array): bool
{
return array_keys($array) === range(0, count($array) - 1);
}
}
$data = [
[
'description' => 'Foo',
'price' => 1.99,
],
[
'description' => 'Bar',
'price' => 2.88,
],
[
'description' => 'Baz',
'price' => 3.77,
],
[
'description' => 'Bay',
'price' => 4.66,
],
];
class Element implements \Stringable
{
private array $attributes = [];
private ?array $children = null;
public function __construct(
private string $name,
) { }
public function __invoke(...$args): static|string
{
if (array_is_list($args)) {
$this->children = $args;
return $this->__toString();
}
$this->attributes = $args;
return $this;
}
public function __toString(): string
{
$rendered = '<' . $this->name;
foreach ($this->attributes as $attribute => $value) {
$rendered .= ' ' . $attribute;
if ($value !== true) {
$rendered .= '="' . htmlentities($value) . '"';
}
}
$rendered .= '>';
if ($this->children) {
$rendered .= implode('', $this->children) . '</' . $this->name . '>';
}
return $rendered;
}
}
$elements = [
'table',
'th',
'tr',
'td',
];
foreach ($elements as $element) {
$$element = new Element($element);
}
echo $table(id: 'table-id')(
$tr(
$th('Description'),
$th(class: 'text-right')('Price'),
),
...array_map(fn(array $row) =>
$tr(
$td($row['description']),
$td(number_format($row['price'], 2)),
),
$data,
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment