By meez


2019-07-09 11:39:34 8 Comments

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 }}?

1 comments

@Sarah C 2019-07-10 13:46:39

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">

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] Add a class to a image for a specific view

  • 2019-10-23 14:55:26
  • Ruby232
  • 31 View
  • 0 Score
  • 1 Answer
  • Tags:   views 8

2 Answered Questions

Cannot add CSS class to views field

  • 2018-01-26 17:28:10
  • crayden
  • 516 View
  • 0 Score
  • 2 Answer
  • Tags:   views

1 Answered Questions

How to add condition for 1st Iteration in views-view-fields.html.twig file

  • 2017-12-03 06:10:45
  • Debasish
  • 1112 View
  • 1 Score
  • 1 Answer
  • Tags:   theming

3 Answered Questions

[SOLVED] Add a table class name to a View table

  • 2018-10-29 16:14:26
  • paulcap1
  • 693 View
  • 1 Score
  • 3 Answer
  • Tags:   views 8 theming

1 Answered Questions

[SOLVED] Specifying a CSS class for a view

  • 2012-04-10 14:57:45
  • John81
  • 7035 View
  • 1 Score
  • 1 Answer
  • Tags:   7 views theming

1 Answered Questions

[SOLVED] How to add a class for different fields of a view?

  • 2016-08-26 04:42:37
  • Sujan Shrestha
  • 720 View
  • 3 Score
  • 1 Answer
  • Tags:   views theming 8

2 Answered Questions

[SOLVED] Add CSS class to view fields

  • 2015-05-17 18:51:44
  • David
  • 2615 View
  • 1 Score
  • 2 Answer
  • Tags:   views

1 Answered Questions

[SOLVED] Css class for Custom Content type fields

  • 2014-10-09 14:08:41
  • Manu
  • 795 View
  • 0 Score
  • 1 Answer
  • Tags:   views 7 nodes

1 Answered Questions

How to get the custom class added to a view

  • 2013-08-11 13:32:52
  • Oskar Calvo
  • 163 View
  • 0 Score
  • 1 Answer
  • Tags:   7 views theming

Sponsored Content