image.field.inc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * @file
  4. * Implement an image field, based on the file module's file field.
  5. */
  6. use Drupal\Core\Render\Element;
  7. /**
  8. * Prepares variables for image widget templates.
  9. *
  10. * Default template: image-widget.html.twig.
  11. *
  12. * @param array $variables
  13. * An associative array containing:
  14. * - element: A render element representing the image field widget.
  15. */
  16. function template_preprocess_image_widget(&$variables) {
  17. $element = $variables['element'];
  18. $variables['attributes'] = ['class' => ['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']];
  19. $variables['data'] = [];
  20. foreach (Element::children($element) as $child) {
  21. $variables['data'][$child] = $element[$child];
  22. }
  23. }
  24. /**
  25. * Prepares variables for image formatter templates.
  26. *
  27. * Default template: image-formatter.html.twig.
  28. *
  29. * @param array $variables
  30. * An associative array containing:
  31. * - item: An ImageItem object.
  32. * - item_attributes: An optional associative array of html attributes to be
  33. * placed in the img tag.
  34. * - image_style: An optional image style.
  35. * - url: An optional \Drupal\Core\Url object.
  36. */
  37. function template_preprocess_image_formatter(&$variables) {
  38. if ($variables['image_style']) {
  39. $variables['image'] = [
  40. '#theme' => 'image_style',
  41. '#style_name' => $variables['image_style'],
  42. ];
  43. }
  44. else {
  45. $variables['image'] = [
  46. '#theme' => 'image',
  47. ];
  48. }
  49. $variables['image']['#attributes'] = $variables['item_attributes'];
  50. $item = $variables['item'];
  51. // Do not output an empty 'title' attribute.
  52. if (mb_strlen($item->title) != 0) {
  53. $variables['image']['#title'] = $item->title;
  54. }
  55. if (($entity = $item->entity) && empty($item->uri)) {
  56. $variables['image']['#uri'] = $entity->getFileUri();
  57. }
  58. else {
  59. $variables['image']['#uri'] = $item->uri;
  60. }
  61. foreach (['width', 'height', 'alt'] as $key) {
  62. $variables['image']["#$key"] = $item->$key;
  63. }
  64. }