parisek/twig-attribute

A Twig extension for adding attributes to an element

v1.4.1 2023-09-24 13:20 UTC

This package is auto-updated.

Last update: 2024-03-24 14:21:40 UTC


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.

Use Cases