Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Last active July 6, 2021 10:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotrpog/1b022b64c98dbe2c20d71d01416b9fbc to your computer and use it in GitHub Desktop.
Save piotrpog/1b022b64c98dbe2c20d71d01416b9fbc to your computer and use it in GitHub Desktop.
Twig macro turning youtube video URL into responsive and lazy-loaded player. More info: http://craftsnippets.com/articles/responsive-and-lazy-loaded-youtube-videos-with-craft-cms
{# v2 #}
{%- macro ytAddress(url, lazy = true) -%}
{% if url is not empty %}
{% set id = url|split('v=')|last %}
{% set id = id|split('&')|first %}
{% set id = id|split('/')|last %}
<div class="youtube-player">
<figure style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; margin: 0px;">
<iframe src="https://www.youtube.com/embed/{{id}}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"{{ lazy ? ' loading="lazy"'}}></iframe>
</figure>
</div>
{% endif %}
{%- endmacro -%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment