image.field.inc 1.91 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Implement an image field, based on the file module's file field.
 */

8
use Drupal\Core\Render\Element;
9

10
/**
11 12 13
 * Prepares variables for image widget templates.
 *
 * Default template: image-widget.html.twig.
14
 *
15
 * @param array $variables
16 17
 *   An associative array containing:
 *   - element: A render element representing the image field widget.
18
 */
19
function template_preprocess_image_widget(&$variables) {
20 21
  $element = $variables['element'];

22
  $variables['attributes'] = ['class' => ['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']];
23

24
  $variables['data'] = [];
25 26 27 28
  foreach (Element::children($element) as $child) {
    $variables['data'][$child] = $element[$child];
  }

29 30 31
}

/**
32 33 34
 * Prepares variables for image formatter templates.
 *
 * Default template: image-formatter.html.twig.
35
 *
36
 * @param array $variables
37
 *   An associative array containing:
38 39 40
 *   - item: An ImageItem object.
 *   - item_attributes: An optional associative array of html attributes to be
 *     placed in the img tag.
41
 *   - image_style: An optional image style.
42
 *   - url: An optional \Drupal\Core\Url object.
43
 */
44
function template_preprocess_image_formatter(&$variables) {
45
  if ($variables['image_style']) {
46
    $variables['image'] = [
47 48
      '#theme' => 'image_style',
      '#style_name' => $variables['image_style'],
49
    ];
50 51
  }
  else {
52
    $variables['image'] = [
53
      '#theme' => 'image',
54
    ];
55
  }
56
  $variables['image']['#attributes'] = $variables['item_attributes'];
57

58
  $item = $variables['item'];
59

60
  // Do not output an empty 'title' attribute.
61
  if (mb_strlen($item->title) != 0) {
62
    $variables['image']['#title'] = $item->title;
63
  }
64

65
  if (($entity = $item->entity) && empty($item->uri)) {
66
    $variables['image']['#uri'] = $entity->getFileUri();
67 68
  }
  else {
69
    $variables['image']['#uri'] = $item->uri;
70 71
  }

72
  foreach (['width', 'height', 'alt'] as $key) {
73
    $variables['image']["#$key"] = $item->$key;
74
  }
75
}