Twig is desperately missing wrapper function to handle HTML Attributes. I borrowed great Attribute class from Drupal. It collects, sanitizes, and renders HTML attributes in a nice way.
This package was created based on issue #2664570 - Move Attribute classes under Drupal\Component which created groundwork for using this class outside Drupal world. Unfortunately I had to copy code out because issue is still open. I hope issue will be merged soon, so I can switch to official component split off from Drupal core with proper attribution. Expected component should be available at https://github.com/drupal/core-attribute
Twig Attribute Extension can be easily installed using composer
composer require parisek/twig-attribute
$twig = new Twig_Environment($loader);
$twig->addExtension(new Parisek\Twig\AttributeExtension());
To use in a symfony project register the extensions as a service.
services:
twig.extension.attribute:
class: Parisek\Twig\AttributeExtension
tags:
- { name: twig.extension }
{% set my_attribute = create_attribute() %}
{%
set my_classes = [
'kittens',
'llamas',
isKitten ? 'cats' : 'dogs',
]
%}
<div{{ my_attribute.addClass(my_classes).setAttribute('id', 'myUniqueId') }}>
{{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
{{ content }}
</div>
Examples were copied from official Drupal documentation.