image.field.inc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. if (!empty($element['fids']['#value'])) {
  20. $file = reset($element['#files']);
  21. $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
  22. }
  23. $variables['data'] = [];
  24. foreach (Element::children($element) as $child) {
  25. $variables['data'][$child] = $element[$child];
  26. }
  27. }
  28. /**
  29. * Prepares variables for image formatter templates.
  30. *
  31. * Default template: image-formatter.html.twig.
  32. *
  33. * @param array $variables
  34. * An associative array containing:
  35. * - item: An ImageItem object.
  36. * - item_attributes: An optional associative array of html attributes to be
  37. * placed in the img tag.
  38. * - image_style: An optional image style.
  39. * - url: An optional \Drupal\Core\Url object.
  40. */
  41. function template_preprocess_image_formatter(&$variables) {
  42. if ($variables['image_style']) {
  43. $variables['image'] = [
  44. '#theme' => 'image_style',
  45. '#style_name' => $variables['image_style'],
  46. ];
  47. }
  48. else {
  49. $variables['image'] = [
  50. '#theme' => 'image',
  51. ];
  52. }
  53. $variables['image']['#attributes'] = $variables['item_attributes'];
  54. $item = $variables['item'];
  55. // Do not output an empty 'title' attribute.
  56. if (mb_strlen($item->title) != 0) {
  57. $variables['image']['#title'] = $item->title;
  58. }
  59. if (($entity = $item->entity) && empty($item->uri)) {
  60. $variables['image']['#uri'] = $entity->getFileUri();
  61. }
  62. else {
  63. $variables['image']['#uri'] = $item->uri;
  64. }
  65. foreach (['width', 'height', 'alt'] as $key) {
  66. $variables['image']["#$key"] = $item->$key;
  67. }
  68. }