image.field.inc 2.2 KB

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