Skip to content

Instantly share code, notes, and snippets.

@heitoralthmann
Created November 20, 2019 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heitoralthmann/45363a657f39a71f9ebe08ec1541fbb0 to your computer and use it in GitHub Desktop.
Save heitoralthmann/45363a657f39a71f9ebe08ec1541fbb0 to your computer and use it in GitHub Desktop.
How to add css classes to the <img> tag generated by an image field (Drupal 8)
<?php
/**
* @file
* Functions to support theming in the THEME_NAME theme.
*/
/**
* Implements hook_preprocess_theme().
*/
function THEME_NAME_preprocess_field(&$variables, $hook) {
$element = &$variables['element'];
if ($element['#field_type'] === 'image') {
$delta = 0;
while (!empty($element[$delta])) {
// Initialize the classes array in case it doesn't exist.
$variables['items'][$delta]['content']['#item_attributes']['class'] = $variables['items'][$delta]['content']['#item_attributes']['class'] ?? [];
$variables['items'][$delta]['content']['#item_attributes']['class'] = array_merge(
$variables['items'][$delta]['content']['#item_attributes']['class'],
_get_css_classes_for_image_field($element['#field_name'])
);
$delta++;
}
}
}
/**
* Gets css classes for a given (image) field name.
*
* @param string $field_name
* The name of the field to have css classes added to.
*
* @return string[]
* An array of classes to be applied
* or an empty array in case none are available.
*/
function _get_css_classes_for_image_field(string $field_name): array {
$classes = _get_image_field_class_mapping();
return $classes[$field_name] ?? [];
}
/**
* Gets a list of desidered classes by field name.
*
* This method in intended to use as the data source for adding specific
* css classes to the <img> tag of some image fields.
*
* @return array
* The class mapping in the format {field_name: [desire_class_names]}
*/
function _get_image_field_class_mapping(): array {
return [
'FIELD_NAME' => ['CSS_CLASS_1', 'CSS_CLASS_2'],
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment