Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By davidhernandez on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.0.x
Issue links:
Description:
Two methods have been added to the Attribute class for setting and removing attributes. They are setAttribute() and removeAttribute().
setAttribute will accept the name of the attribute and its value. removeAttribute will accept only the name of the attribute to be removed.
Twig Examples
Setting
<div{{ attributes.setAttribute('id', 'foo') }}>
Setting with an array
<div{{ attributes.setAttribute('class', ['red', 'green', 'blue']) }}>
Note: It is not recommend that you use setAttribute for classes. Use addClass(). See https://www.drupal.org/node/2315471
Removing
<div{{ attributes.removeAttribute('role') }}>
Removing multiple attributes
<div{{ attributes.removeAttribute('id', 'role') }}>
PHP Examples (assuming an Attribute object already exists.)
Setting
$attribute->setAttribute('id', 'foo');
Setting with an array
$attribute->setAttribute('class', array('red', 'green', 'blue'));
Removing
$attribute->removeAttribute('role');
Removing multiple attributes
$attribute->removeAttribute('id', 'role');
Impacts:
Module developers
Themers