Imagine that you are developing a blog overview page, and for each post, you want to show images, music, or videos in that page taken from the content. In such a case, you need to extract the <figure>
, <img>
, <object>
, <embed>
, <video>
, <audio>
, and <iframe>
tags from the HTML content of the post. In this recipe, we will see how to perform this using regular expressions in the first_media
filter.
We will start with the utils
app that should be set in INSTALLED_APPS
in the settings and the templatetags
package in this app.
In the utility_tags.py
file, add the following content:
# utils/templatetags/utility_tags.py
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import re
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
### FILTERS ###
media_tags_regex = re.compile(
r"<figure[\S\s]+...