Hi.

Not sure if it is the correct section here… if not, please move or advise…

I want to have a video poster in the file > video field. I have not yet been able to find a practicable solution. So i thought i can do this by simply adding the url for the poster image inside the <video> tag. But i don't know how to get the url value as a token working in twig. I am also not sure if the image would be from the actual node. Maybe this apporach is not even working.

<video {{ attributes }} poster="{{ url of the field_image }}">
  {% for file in files %}
    <source {{ file.source_attributes }} />
  {% endfor %}
</video>

Can someone help?

Thanks

Comments

stixer’s picture

I found this working, it displays the url in my page.html.twig correct (just for testing):

{{ file_url(node.field_image.0.entity.uri.value) }}

But here it is not working, the output is empty:

<video {{ attributes }} poster="{{ file_url(node.field_image.0.entity.uri.value) }}">
  {% for file in files %}
    <source {{ file.source_attributes }} />
  {% endfor %}
</video>
wombatbuddy’s picture

Let's assume the video field is named "field_video" and the image field is named "field_video_poster". Since the use case assumes that the video field will have a single video file, the following solution is possible:

1. Create a copy of "field.html.twig" and rename it to "field--field-video.html.twig".

2. Copy the following code to the YOUR_THEME.theme file: 

use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_preprocess_HOOK() for field_video template.
 */
function YOUR_THEME_NAME_preprocess_field__field_video(&$variables) {
  $node = $variables['element']['#object'];
  $videoPosterOriginalUrl = $node->field_video_poster->entity->getFileUri();
  // Feel free to replace the "medium" image style with yours.
  $videoPosterStyledUrl = ImageStyle::load('medium')->buildUrl($videoPosterOriginalUrl);
  $variables['items'][0]['content']['#attributes']->setAttribute('poster', $videoPosterStyledUrl);
}

3. Rebuild the caches.

As an alternative solution, you can try the Video module and the patch from the #3177537 issue.
Also in the #2954834 issue, work is underway to add this feature to the core Media module.

stixer’s picture

Thanks so much … works smoothly, great solution!