Skip to content

Instantly share code, notes, and snippets.

@goldhand
Last active May 17, 2022 21:00
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save goldhand/2f4bc7b1bb2cba76919b to your computer and use it in GitHub Desktop.
Save goldhand/2f4bc7b1bb2cba76919b to your computer and use it in GitHub Desktop.
Django template tag for encoding images in base64 and rendering with server
from django import template
from django.contrib.staticfiles.finders import find as find_static_file
from django.conf import settings
register = template.Library()
@register.simple_tag
def encode_static(path, encoding='base64', file_type='image'):
"""
a template tag that returns a encoded string representation of a staticfile
Usage::
{% encode_static path [encoding] %}
Examples::
<img src="{% encode_static 'path/to/img.png' %}">
"""
file_path = find_static_file(path)
ext = file_path.split('.')[-1]
file_str = get_file_data(file_path).encode(encoding)
return u"data:{0}/{1};{2},{3}".format(file_type, ext, encoding, file_str)
@register.simple_tag
def raw_static(path):
"""
a template tag that returns a raw staticfile
Usage::
{% raw_static path %}
Examples::
<style>{% raw_static path/to/style.css %}</style>
"""
if path.startswith(settings.STATIC_URL):
# remove static_url if its included in the path
path = path.replace(settings.STATIC_URL, '')
file_path = find_static_file(path)
return get_file_data(file_path)
def get_file_data(file_path):
with open(file_path, 'rb') as f:
data = f.read()
f.close()
return data
@Pettles
Copy link

Pettles commented May 17, 2019

+1 for this, it's exactly what I needed.

I added a try/except clause in https://gist.github.com/Pettles/23b0d250417ff7183f183a64d8082f06, just because hitting an IOError (or any other exception) prevents the template from rendering entirely. So if one image fails to decode, etc. the while template dies.

Thanks again!

@Genarito
Copy link

Thank you so much! I've implemented a modified version of @Pettles gist to make it work in Python 3.x. Link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment