Skip to content

Instantly share code, notes, and snippets.

@umutcoskun
Created August 30, 2017 08:05
Show Gist options
  • Save umutcoskun/40e73bd0c0a9abc4aeb8623e2958e5d7 to your computer and use it in GitHub Desktop.
Save umutcoskun/40e73bd0c0a9abc4aeb8623e2958e5d7 to your computer and use it in GitHub Desktop.
Django custom template filter that replaces 'img' tags with 'amp-img'. The img tags must have 'height' and 'width' attributes for validated AMP output.
from django import template
register = template.Library()
@register.filter(name='amp')
def amp(value):
"""
Usage:
{{ article.body|amp }}
"""
import re
value = re.sub(
r'<img src="(.+)" alt="(.+)"/?>',
r'<amp-img src="\1" alt="\2" layout="responsive"></amp-img>',
value,
)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment