5 * Implement an image field, based on the file module's file field.
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Render\Element;
12 * Prepares variables for image widget templates.
14 * Default template: image-widget.html.twig.
16 * @param array $variables
17 * An associative array containing:
18 * - element: A render element representing the image field widget.
20 function template_preprocess_image_widget(&$variables) {
21 $element = $variables['element'];
23 $variables['attributes'] = ['class' => ['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']];
25 if (!empty($element['fids']['#value'])) {
26 $file = reset($element['#files']);
27 $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
30 $variables['data'] = [];
31 foreach (Element::children($element) as $child) {
32 $variables['data'][$child] = $element[$child];
38 * Prepares variables for image formatter templates.
40 * Default template: image-formatter.html.twig.
42 * @param array $variables
43 * An associative array containing:
44 * - item: An ImageItem object.
45 * - item_attributes: An optional associative array of html attributes to be
46 * placed in the img tag.
47 * - image_style: An optional image style.
48 * - url: An optional \Drupal\Core\Url object.
50 function template_preprocess_image_formatter(&$variables) {
51 if ($variables['image_style']) {
52 $variables['image'] = [
53 '#theme' => 'image_style',
54 '#style_name' => $variables['image_style'],
58 $variables['image'] = [
62 $variables['image']['#attributes'] = $variables['item_attributes'];
64 $item = $variables['item'];
66 // Do not output an empty 'title' attribute.
67 if (Unicode::strlen($item->title) != 0) {
68 $variables['image']['#title'] = $item->title;
71 if (($entity = $item->entity) && empty($item->uri)) {
72 $variables['image']['#uri'] = $entity->getFileUri();
75 $variables['image']['#uri'] = $item->uri;
78 foreach (['width', 'height', 'alt'] as $key) {
79 $variables['image']["#$key"] = $item->$key;