Using the theme preprocess field function in a Drupal 8 theme

Some powerful stuff!

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_tags field.
  if($variables['element']['#field_name'] == 'field_tags') {
    // Loop over the available tags.
    foreach($variables['items'] as $key => $value) {
      $variables['items'][$key]['content']['#attributes']['class'][] = \Drupal\Component\Utility\Html::getClass('test-class '.$key+1);

Note that there is a space in my class, the usage of Html::getClass will make sure a valid class is used (thanks @marcvangend for the usefull information)

If you would have a node with 3 tags now their respective classes would be:

  • First term reference: test-class-1
  • Second term reference: test-class-2
  • Third term reference: test-class-3

Happy theming!


Meer leesvoer

I have been working on a Drupal 8 multisite and at some point I had to set up a new site in the structure. The...
In this blog post I show you how to login and logout from a Drupal 8 Back-end from an Ionic app
It's quite easy to create a node with REST in Drupal 8, in this blog post I'll show you how to do it.
Drupal 8.3-x-dev is out and it comes packed with improvements to the REST module. It's now possible to create new users using REST.