2

I want to be able to upload and play videos on my Craft CMS website.

I created a volume and field to hold these videos. So far so good, but whenever I want to output the video in a video tag I'm not sure how to get the URL of the video.

My code:

{% set video = component.video %}
{% if video %}
   <video width="800" height="500" controls>
      <source src="## VIDEO URL ##" type="video/mp4">
   </video>
{% endif %}
3

You're close!

Because an asset field can potentially contain multiple items you need to explicitly select the first one, so:

{% set video = component.video.one() %}

But that doesn't get the actual url of the video, to get that you need to request it:

{{ video.url() }}

So in your case:

{% set video = component.video.one() %}
{% if video %}
   <video width="800" height="500" controls>
      <source src="{{ video.url() }}" type="video/mp4">
   </video>
{% endif %}

If you do find yourself needing to show multiple files, then you'd wrap it within a loop:

{# Get all the files #}
{% set videos = component.video.all() %}

{# Check to see if videos has anything in it with '|length' #}
{% if videos|length %}
    {% for video in videos %}
       <video width="800" height="500" controls>
          <source src="{{ video.url() }}" type="video/mp4">
       </video>
    {% endfor %}
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.