A tiny php attribute helper
composer require hirasso/attr
Define your attributes in an associative way:
<button <?= attr([
'type' => 'button',
'class' => [
'button button--primary' => true,
'button--active' => $is_active
],
'style' => [
'--color' => 'red'
],
'data-toggle' => true
]) ?>>
Click Me!
</button>
...and the attr
function transforms them into normal HTML:
<button
type="button"
class="button button--primary button--active"
style="--color: red;"
data-toggle
>
Click Me!
</button>
Render JSON so that it is safe to be used inside an HTMLElement attribute:
/** Example: render an attribute to be used by Alpine.js */
<div <?= attr([
'x-data' => jsonAttr([
'open' => true,
"message" => "This 'quote' is <b>bold</b>"
])
]) ?>>
</div>
..the output will look like this and can be consumed by JavaScript:
<div x-data="{"open":true,"message":"This 'quote' is <b>bold<\/b>"}"></div>