7

I have a client with a Drupal 8 site who prefers curly quotes to straight quotes. I have successfully made this change for node titles using a regex replacement in template_preprocess_page_title. Now I am trying to accomplish the same thing for a different text field that is rendered by a view, using template_preprocess_views_view_field or template_preprocess_views_view_fields, but for the life of me I cannot figure out how to get individual field values using this function. Am I even trying the correct preprocess functions?

I have also tried rewriting the output of the field by accessing the variable in a custom twig template, with poor results.

1 Answer 1

16

It depends how you have your view set up.

If you have your view using the format 'Fields' then you can override the content with template_preprocess_views_view_field() like you say, like this (although you might want to target individual fields with some if statements):

/**
 * Implements hook_preprocess_HOOK() for views-view-field.html.twig.
 */
function THEMENAME_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_NAME') {
      // Replace characters in the field output.
      $variables['output'] = Drupal\Core\Render\Markup::create(str_replace('find', 'replace', $variables['output']));
    }
  }
}

If you are using the format 'Content' then you could do it at the field template level or node template level instead, since in that case it doesn't use the views field templates.

8
  • This is really helpful. I am using the 'Fields' format in my view. Applying the replacement across the board breaks the view, so I do need to target an individual field. I'm having trouble seeing how to do this in the preprocess function, though. It was easy in Drupal 7. My field name is field_home_page_headline. Can you assist?
    – JOakland
    Commented Oct 2, 2017 at 16:52
  • @JOakland I updated the example with some checks for views name & display and the field name.
    – rooby
    Commented Oct 4, 2017 at 10:53
  • That did it! Thank you for taking the time to help me resolve this. I've been banging my head against the D8 documentation for days.
    – JOakland
    Commented Oct 4, 2017 at 16:41
  • @rooby How can i use the updated field value in view custom field ?
    – Raj Ghai
    Commented Apr 3, 2018 at 8:12
  • @RajGhai what do you mean by view custom field?
    – rooby
    Commented Apr 3, 2018 at 9:22

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.