Problem/Motivation
#2285451: Create addClass() and removeClass() methods on Attribute object for merging css class names. added methods on the Attribute class to add and remove CSS classes. This is super useful and a key part of #2322163: [meta] Consensus Banana Phase 1, move CSS classes from preprocess to twig templates..
It would also be useful to have methods for adding/removing non-class attributes so that this could be done cleanly from within Twig templates.
Proposed resolution
Add methods to the Attribute object for adding/removing attributes, some proposed method names (we would only add one set, we need to pick from these or come up with another set):
set/remove
setAttribute/removeAttribute
setAttribute would accept the attribute name and value.
removeAttribute would accept the attribute name only.
Example syntax within a Twig template:
set/remove:
{% set classes = [
'test1',
'test2',
'test3',
'test4',
]
%}
<div {{ attributes.addClass(classes).set('data-foo', 'bar').remove('role') }}></div>
setAttribute/removeAttribute:
{% set classes = [
'test1',
'test2',
'test3',
'test4',
]
%}
<div {{ attributes.addClass(classes).setAttribute('data-foo', 'bar').removeAttribute('role') }}></div>
Remaining tasks
Patch
Tests
User interface changes
n/a
API changes
API addition to be able to manipulate non-class attributes on Attribute objects.