Change record status: 
Project: 
Introduced in branch: 
8.0.x
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:

  1. If attributes.class is empty there will be a space in the markup.
  2. For removal we needed to normalize the class string to remove the jazzberry class without removing a jazzberry-jam class
  3. 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:

  1. 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

Kai’s picture

Example for adding a css class called "block" to every block

function theme_preprocess_block(&$variables) {
  $variables['attributes'] = new Drupal\Core\Template\Attribute($variables['attributes']);
  $variables['attributes']->addClass('block');
}
galactus86’s picture

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?

diamondsea’s picture

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)