In the utility_tags.py file, add the following content:
# utils/templatetags/utility_tags.py
import re
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
"""FILTERS"""
MEDIA_CLOSED_TAGS = "|".join([
"figure", "object", "video", "audio", "iframe"])
MEDIA_SINGLE_TAGS = "|".join(["img", "embed"])
MEDIA_TAGS_REGEX = re.compile(
r"<(?P<tag>" + MEDIA_CLOSED_TAGS + ")[Ss]+?</(?P=tag)>|" +
r"<(" + MEDIA_SINGLE_TAGS + ")[^>]+>",
re.MULTILINE)
@register.filter
def first_media(content):
"""
Returns the chunk of media-related markup from the html content
"""
tag_match = MEDIA_TAGS_REGEX.search(content)
media_tag = ""
if tag_match:
media_tag = tag_match.group()
return mark_safe(media_tag)