In my custom view fields twig file views-view-fields--search--product_result.html.twig I try to theme my view item.

{{ fields.field_images.content }}
<h5 class="card-title">{{ fields.title.content }}</h5>

How do I add a CSS class to my image field {{ fields.field_images.content }}?

  • In a Views field(s) template you can't theme field content anymore because it has already been rendered.
    – 4k4
    Jul 9 '19 at 11:45
  • @4k4 Ok so what's the solution. Traditional way through Views ui and rewrite fields content?
    – meez
    Jul 9 '19 at 11:53
  • Yes, before you rewrite the field try to add the CSS class in Style Settings of the field.
    – 4k4
    Jul 9 '19 at 12:02
  • @4k4 I think it's not possible for a field which is Exclude from display? I tried but it's stripped...
    – meez
    Jul 9 '19 at 12:14
  • OK, when you exclude from display and use field tokens you have total control over the markup and you don't need the Style Settings anymore.
    – 4k4
    Jul 9 '19 at 12:31

This is what worked for me: It's a preprocess function in the .theme file. I wish there was a way to do this directly into the template. This would apply that class everywhere the field appears.

 * Implements hook_preprocess_field().
 * Adds a class to a People image.
function themename_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_machine_name') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'my_class';

themename, field_machine_name, and my_class are placeholders for your values.

This produces:

<img class="my_class" src="/your/image/location.png" alt="Your alt text." typeof="foaf:Image" width="458" height="354">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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