HtmxAttribute objects
HTMX implements its actions using attributes on HTML entities. This module
provides an extension of Drupal\Core\Template\Attribute
that has methods
for assembling these attributes. This approach documents and provides
type safety for the content of the HTMX attributes.
Each method on \Drupal\htmx\Template\HtmxAttribute
also links to the matching
HTMX documentation in its associated DocBlock.
Using in unaltered markup
Because HtmxAttribute
is an Attribute
object, you can send it directly to
be rendered if you know that no other code will be altering the render
attributes.
$htmxClose = new HtmxAttribute([
'class' => [
'button',
'button--action',
'button--primary',
'ui-button-icon-only',
'ui-dialog-titlebar-close',
'button--htmx',
],
]);
$htmxClose->on('click', 'removeOffCanvasDialog(this)');
$build = [
'close' => [
'#type' => 'inline_template',
'#template' => '<button {{ attributes }} ><span class="default-text">{{ closeLabel }}</span></button>',
'#context' => [
'closeLabel' => $this->t('Close'),
'attributes' => $htmxClose,
],
],
];
Using in markup that may be altered
However, if you are altering a render array you should convert back to an array so that any alter hooks can add additional attributes since those implementations will not be expecting an Attribute object.
$htmxAddButton = new HtmxAttribute($row['operations']['data']['#attributes']);
$htmxAddButton->get(Url::fromRoute('entity.htmx_block.add_form', ['plugin_id' => $plugin_id]))
->target('#drupal-off-canvas-wrapper')
->select('#drupal-off-canvas-wrapper')
->swap('outerHTML');
$row['operations']['data']['#attributes'] = $htmxAddButton->toArray();
Twig function
A Twig function, create_htmx
, is provided that will return a new
HtmxAttribute
is also provided. You will need a url object to add any
requests. The Twig Tweak module provides a drupal_url
function that you can use to get a Url object in Twig.