Browse Source

Add title to embedded iframes (#207)

Fixes #196 and improves AMP rendering of some embedded iframes
Cory Sutyak 5 years ago
parent
commit
5975de9b7a

+ 9 - 2
coderedcms/templates/coderedcms/blocks/embed_video_block.html

@@ -1,5 +1,12 @@
 {% extends "coderedcms/blocks/base_block.html" %}
+{% load coderedcms_tags %}
 
 {% block block_render %}
-{{self.url}}
-{% endblock %}
+
+{% if format == 'amp' %}
+    {{ self.url.html|amp_formatting }}
+{% else %}
+    {{ self.url }}
+{% endif %}
+
+{% endblock %}

+ 1 - 1
coderedcms/templates/coderedcms/blocks/rich_text_block.html

@@ -3,7 +3,7 @@
 {% block block_render %}
 
 {% if format == 'amp' %}
-{{ self|richtext_amp }}
+{{ self|richtext_amp_formatting }}
 {% else %}
 {{ self|richtext }}
 {% endif %}

+ 1 - 0
coderedcms/templates/coderedcms/pages/base.amp.html

@@ -208,6 +208,7 @@
     </style>
     <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
     <script async src="https://cdn.ampproject.org/v0.js"></script>
+    <script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
   </head>
   <body>
     {% block amp_nav %}

+ 2 - 3
coderedcms/templates/wagtailembeds/embed_frontend.html

@@ -1,4 +1,4 @@
-{% load wagtailembeds_tags %}
+{% load coderedcms_tags %}
 
 {% if embed.ratio %}
     {# If an aspect ratio is included, use the appropriate Bootstrap 4 class #}
@@ -16,6 +16,5 @@
     <div class="row justify-content-center">
 {% endif %}
 
-{# Embed the video with an absurdly high max width. #}
-{% embed embed.url max_width=3840 %}
+{% render_iframe_from_embed embed %}
 </div>

+ 41 - 24
coderedcms/templatetags/coderedcms_tags.py

@@ -1,13 +1,11 @@
 import string
 import random
-from html import unescape
-
 
+from bs4 import BeautifulSoup
 from datetime import datetime
 from django import template
 from django.conf import settings
 from django.forms import ClearableFileInput
-from django.utils import timezone
 from django.utils.html import mark_safe
 from wagtail.core.models import Collection
 from wagtail.core.rich_text import RichText
@@ -22,49 +20,37 @@ from coderedcms.settings import cr_settings, get_bootstrap_setting
 
 register = template.Library()
 
-@register.filter
-def get_embed_video_provider(url):
-    if 'youtu.be' in url or 'youtube.com' in url:
-        return 'youtube'
-    if 'vimeo.com' in url:
-        return 'vimeo'
-    return ''
-
-@register.filter
-def get_embed_video_code(url):
-    if get_embed_video_provider(url) == 'youtube':
-        v = url.split('v=', 1)[1]
-        return v.split('&', 1)[0]
-    if get_embed_video_provider(url) == 'vimeo':
-        v = url.split('.com/', 1)[1]
-        return v.split('?', 1)[0]
-    return ''
 
 @register.filter
 def is_advanced_setting(obj):
     return CoderedAdvSettings in (obj.__class__,) + obj.__class__.__bases__
 
+
 @register.filter
 def is_file_form(form):
     return any([isinstance(field.field.widget, ClearableFileInput) for field in form])
 
+
 @register.simple_tag
 def coderedcms_version():
     return __version__
 
+
 @register.simple_tag
 def generate_random_id():
     return ''.join(random.choice(string.ascii_letters + string.digits) for n in range(20))
 
+
 @register.simple_tag
 def is_menu_item_dropdown(value):
     return \
         len(value.get('sub_links', [])) > 0 or \
         (
-            value.get('show_child_links', False) and \
+            value.get('show_child_links', False) and
             len(value.get('page', []).get_children().live()) > 0
         )
 
+
 @register.simple_tag(takes_context=True)
 def is_active_page(context, curr_page, other_page):
     if hasattr(curr_page, 'get_url') and hasattr(other_page, 'get_url'):
@@ -73,29 +59,35 @@ def is_active_page(context, curr_page, other_page):
         return curr_url == other_url
     return False
 
+
 @register.simple_tag
 def get_pictures(collection_id):
     collection = Collection.objects.get(id=collection_id)
     return Image.objects.filter(collection=collection)
 
+
 @register.simple_tag
 def get_navbars():
     return Navbar.objects.all()
 
+
 @register.simple_tag
 def get_footers():
     return Footer.objects.all()
 
+
 @register.simple_tag
 def get_searchform(request=None):
     if request:
         return SearchForm(request.GET)
     return SearchForm()
 
+
 @register.simple_tag
 def get_pageform(page, request):
     return page.get_form(page=page, user=request.user)
 
+
 @register.simple_tag
 def process_form_cell(request, cell):
     if isinstance(cell, str) and cell.startswith(cr_settings['PROTECTED_MEDIA_URL']):
@@ -104,18 +96,22 @@ def process_form_cell(request, cell):
         return mark_safe("<a href='{0}'>{1}</a>".format(cell, cell))
     return cell
 
+
 @register.filter
 def codered_settings(value):
     return cr_settings.get(value, None)
 
+
 @register.filter
 def bootstrap_settings(value):
     return get_bootstrap_setting(value)
 
+
 @register.filter
 def django_settings(value):
     return getattr(settings, value)
 
+
 @register.simple_tag
 def query_update(querydict, key=None, value=None):
     """
@@ -132,6 +128,7 @@ def query_update(querydict, key=None, value=None):
                 pass
     return get
 
+
 @register.filter
 def structured_data_datetime(dt):
     """
@@ -141,13 +138,33 @@ def structured_data_datetime(dt):
         return datetime.strftime(dt, "%Y-%m-%dT%H:%M")
     return datetime.strftime(dt, "%Y-%m-%d")
 
+
 @register.filter
-def richtext_amp(value):
+def amp_formatting(value):
+    return mark_safe(utils.convert_to_amp(value))
+
+
+@register.filter
+def richtext_amp_formatting(value):
 
     if isinstance(value, RichText):
         value = richtext(value.source)
     else:
         value = richtext(value)
 
-    value = utils.convert_to_amp(value)
-    return mark_safe(value)
+    return amp_formatting(value)
+
+
+@register.simple_tag
+def render_iframe_from_embed(embed):
+    soup = BeautifulSoup(embed.html, "html.parser")
+    try:
+        iframe_tags = soup.find('iframe')
+        iframe_tags['title'] = embed.title
+        return mark_safe(soup.prettify())
+    except AttributeError:
+        pass
+    except TypeError:
+        pass
+
+    return mark_safe(embed.html)

+ 11 - 2
coderedcms/utils.py

@@ -44,13 +44,22 @@ def convert_to_amp(value):
     Function that converts non-amp compliant html to valid amp html.
     value must be a string
     """
-    soup = BeautifulSoup(value)
+    soup = BeautifulSoup(value, "html.parser")
 
-    #Replace img tags with amp-img
+    # Replace img tags with amp-img
     try:
         img_tags = soup.find('img')
         img_tags.name = 'amp-img'
     except AttributeError:
         pass
 
+    # Replace iframe tags with amp-iframe
+    try:
+        iframe_tags = soup.find('iframe')
+        iframe_tags.name = 'amp-iframe'
+        iframe_tags['layout'] = 'responsive'
+
+    except AttributeError:
+        pass
+
     return soup.prettify()