How to add a taxonomy term value as a class? I am trying to target a specific div with CSS. But for that, I need a unique class in order to target a specific taxonomy term. I look at this question, but that doesn't work as it will target all taxonomy terms.

I have created a vocabulary called 'Titles' which has the following terms in it:


  


Which will display the following in my browser:


  


Note that I am not using a view to display these titles. Instead, I used a preprocess function:

function MYTHEME_preprocess_node(&amp;$variables) {
  $variables['authortitle'] = \Drupal::entityTypeManager()-&gt;getViewBuilder('user')-&gt;view($variables['node']-&gt;getOwner(), 'nodetitle');
}


How can I add "Writer" as a class to the &lt;a&gt; tag?
To append a term's name as CSS class to the term field itself you could simply implement template_preprocess_field() like so:

use Drupal\taxonomy\Entity\Term;
use Drupal\Component\Utility\Html;

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&amp;$variables) {

  if ($variables['field_name'] == 'field_MYFIELD') {

    if (!$variables['element']['#items']-&gt;isEmpty()) {

      // Get the term ID.
      $tid = $variables['element']['#items']-&gt;getValue()[0]['target_id'];

      // Load the term.
      $term = Term::load($tid);

      // Get the term name.
      $name = $term-&gt;getName();

      // Make the term name safe to be used as CSS class.
      $name_safe = strtolower(Html::cleanCssIdentifier($name));

      // Append class.
      $variables['attributes']['class'][] = $name_safe;
    };
  }
}