How to set a dynamic class on every taxonomy term using the theme field preprocess function

Preprocess field

How to set a dynamic class on every taxonomy term using the theme field preprocess function

In this blog post you will learn how to add a theme field preprocess function in your theme. In this specific case we will add a class to every Term reference of the field_tags field.

in your [themename].theme file add the following code:

/*
 * Implements theme_preprocess_fields().
 */
function YOURTHEMENAME_preprocess_field(&$variables, $hook) {

  // For every field_category field.
  if($variables['element']['#field_name'] == 'field_category') {
    // Loop over the available categories.
    foreach($variables['items'] as $key => $value) {
      // Check if a title is set.
      if(isset($value['content']['#title'])) {
        // Set the class dynamically.
        $variables['items'][$key]['content']['#attributes']['class'][] = \Drupal\Component\Utility\Html::getClass($value['content']['#title']);
      }
    }
  }
}

The usage of Html::getClass will make sure a valid class is used.

Happy theming!