parisek / twig-attribute
A Twig extension for adding attributes to an element
Installs: 1 832
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- drupal/core-render: ^10.0 || ^11.0
- drupal/core-utility: ^10.0 || ^11.0
- twig/twig: ^2.4 || ^3.0
README
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
Installation
Twig Attribute Extension can be easily installed using composer
composer require parisek/twig-attribute
Usage
$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 }
Template
{% 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.