You are here

function template_preprocess_youtube_thumbnail in YouTube Field 8

Prepares variables for the YouTube Thumbnail template.

Default template: youtube-thumbnail.html.twig.

File

./youtube.module, line 224
Youtube field module adds a field for YouTube videos.

Code

function template_preprocess_youtube_thumbnail(&$variables) {
  $video_id = $variables['video_id'];
  $image_style = $variables['image_style'];

  // Build the image element's alt attribute value (for accessibility).
  $alt = t('Embedded thumbnail');
  if (!empty($variables['entity_title'])) {
    $alt .= ' ' . t('for @entity_title', [
      '@entity_title' => $variables['entity_title'],
    ]);
  }

  // Check to see if a thumbnail exists locally.
  $uri = youtube_build_thumbnail_uri($video_id);
  if (!file_exists($uri)) {

    // Retrieve the image from YouTube.
    if (!youtube_get_remote_image($video_id)) {

      // Use the remote source if local copy fails.
      $uri = youtube_build_remote_image_path($video_id);
    }
  }

  // Build the initial image render array.
  $variables['image'] = [
    '#theme' => 'image',
    '#uri' => $uri,
    '#alt' => $alt,
  ];

  // If an image style has been chosen in the field's display settings, alter
  // the render array to use that image style. Remote images cannot be rendered
  // through an image style.
  if ($image_style && empty($remote_uri)) {
    $variables['image']['#theme'] = 'image_style';
    $variables['image']['#style_name'] = $image_style;
  }

  // If a URL path is provided, create a link with the image and that path.
  if ($variables['image_link'] != NULL) {
    $variables['image'] = Link::fromTextAndUrl($variables['image'], $variables['image_link']);
  }
}