Skip to content

Instantly share code, notes, and snippets.

@myles
Created March 28, 2014 21:25
Show Gist options
  • Save myles/9843308 to your computer and use it in GitHub Desktop.
Save myles/9843308 to your computer and use it in GitHub Desktop.
A Django template tag for thumbnailing a block of HTML `img` tag using sorl-thumbnail and BeautifulSoup 4.
from bs4 import BeautifulSoup
from django import template
from sorl.thumbnail.shortcuts import get_thumbnail
from sorl.thumbnail.conf import settings as sorl_settings
register = template.Library()
@register.filter(is_safe=True)
def html_thumbnails(value):
soup = BeautifulSoup(value, "html.parser")
for image in soup.find_all('img'):
thumbnail = get_thumbnail(
image.get('src'),
image.get('geometry', sorl_settings.THUMBNAIL_FILTER_WIDTH),
upscale=False
)
del image['geometry']
image['src'] = thumbnail.url
return str(soup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment