Skip to content

Instantly share code, notes, and snippets.

@piotrpog piotrpog/yt_iframe.twig
Last active Aug 30, 2019

Embed
What would you like to do?
Twig macro making embedded youtube players responsive and lazy-loaded. Requires Craft CMS Retcon plugin, More info: http://craftsnippets.com/articles/responsive-and-lazy-loaded-youtube-videos-with-craft-cms
{# v2 #}
{%- macro ytIframe(html, lazy = true) -%}
{% if html is not empty and craft.app.plugins.isPluginEnabled('retcon') %}
{% set html = html|retconAttr('iframe', {'style' : 'position: absolute; top: 0; left: 0; width: 100%; height: 100%;'} ) %}
{% if lazy %}
{% set html = html|retconAttr('iframe', {'loading' : 'lazy'} ) %}
{% endif %}
{% set html = html|retconWrap( [ 'iframe' ], 'figure') %}
{% set html = html|retconAttr('figure', {'style' : 'position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; margin: 0px;'} ) %}
{% set html = html|retconWrap( [ 'figure' ], 'div.youtube-player') %}
{{html}}
{% endif %}
{%- endmacro -%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.