5 * Implement an image field, based on the file module's file field.
8 use Drupal\Core\Render\Element;
11 * Prepares variables for image widget templates.
13 * Default template: image-widget.html.twig.
15 * @param array $variables
16 * An associative array containing:
17 * - element: A render element representing the image field widget.
19 function template_preprocess_image_widget(&$variables) {
20 $element = $variables['element'];
22 $variables['attributes'] = ['class' => ['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']];
24 if (!empty($element['fids']['#value'])) {
25 $file = reset($element['#files']);
26 $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
29 $variables['data'] = [];
30 foreach (Element::children($element) as $child) {
31 $variables['data'][$child] = $element[$child];
37 * Prepares variables for image formatter templates.
39 * Default template: image-formatter.html.twig.
41 * @param array $variables
42 * An associative array containing:
43 * - item: An ImageItem object.
44 * - item_attributes: An optional associative array of html attributes to be
45 * placed in the img tag.
46 * - image_style: An optional image style.
47 * - url: An optional \Drupal\Core\Url object.
49 function template_preprocess_image_formatter(&$variables) {
50 if ($variables['image_style']) {
51 $variables['image'] = [
52 '#theme' => 'image_style',
53 '#style_name' => $variables['image_style'],
57 $variables['image'] = [
61 $variables['image']['#attributes'] = $variables['item_attributes'];
63 $item = $variables['item'];
65 // Do not output an empty 'title' attribute.
66 if (mb_strlen($item->title) != 0) {
67 $variables['image']['#title'] = $item->title;
70 if (($entity = $item->entity) && empty($item->uri)) {
71 $variables['image']['#uri'] = $entity->getFileUri();
74 $variables['image']['#uri'] = $item->uri;
77 foreach (['width', 'height', 'alt'] as $key) {
78 $variables['image']["#$key"] = $item->$key;