In a view I would like to use a excluded term reference field as source for the the row classname. But the values need to be sanitized by putting the term names through drupal_html_class(), otherwise the resulting classnames are not valid in every case.

How can I sanitize the values using a preprocess function?

1 Answer 1


I got it working by using this preprocess function:

function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'field_category') {
      $tid = $variables['row']->_entity->field_category->target_id;
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->getName();
      $variables['output'] = \Drupal\Component\Utility\Html::cleanCssIdentifier($name);

An alternative would be using mytheme_views_pre_render.

  • I would be very interested, which hook (hook_preprocess_views_view_field or hook_views_pre_render) is best regarding performance and caching.
    – Madam Adam
    Dec 27, 2017 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.