By joelpittet on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.0.x
Issue links:
Description:
Added helper methods to the Attribute class to help manipulate CSS classes in PHP and Twig templates.
Twig before
<main class="{{ attributes.class }} red green blue"{{ attributes }}>
<main class="{{ (' ' ~ attributes.class ~ ' ')|replace({ ' jazzberry ': '' })|trim }}"{{ attributes }}></main>
Notes:
- If attributes.class is empty there will be a space in the markup.
- For removal we needed to normalize the class string to remove the
jazzberryclass without removing ajazzberry-jamclass - All these methods still exist.
Twig after
<main{{ attributes.addClass('red', 'green', 'blue').removeClass('jazzberry') }}>
Alternative #1:
<main{{ attributes.addClass(['red', 'green', 'blue']).removeClass(['jazzberry']) }}>
Alternative #2:
{% set add_classes = ['red', 'green', 'blue'] %}
{% set remove_classes = ['jazzberry'] %}
<main{{ attributes.addClass(add_classes).removeClass(remove_classes) }}>
PHP before
// Add a 'red' class.
$variables['attributes'] = new Attribute();
$variables['attributes']['class'] = array(); // Needed to initialize the AttributeArray object.
$variables['attributes']['class'][] = 'red';
// Alternative to add a 'blue' class.
$variables['attributes'] = new Attribute(array('class' => array('blue')));
// Remove a 'jazzberry' class.
$classes = $variables['attributes']['class']->value();
$variables['attributes']['class'] = array_diff($classes, array('jazzberry'));
Notes:
- All these methods still exist.
PHP after
// Add 'red' and 'blue' classes and remove the 'jazzberry' class.
$variables['attributes'] = new Attribute();
$variables['attributes']->addClass('red', 'blue')->removeClass('jazzberry');
Impacts:
Module developers
Themers
Comments
Adding a class via preprocess hook
Example for adding a css class called "block" to every block
Body classes
Not sure if this is the place to ask a question, but struggling to resolve an issue.
I would like to add a body class to my html.html.twig file, based on a taxonomy term. Is there a way to accomplish this?
is there a variable for taxonomy term that can be accessed and then added to the body class array in the twig template?
Body classes with Context
I don't think this can be done in the templates, but you can probably do it using the Context module, such as https://www.drupal.org/node/1072806#comment-5124596 (a D7 post, but should be similar in D8)