Last active
May 17, 2022 21:00
-
-
Save goldhand/2f4bc7b1bb2cba76919b to your computer and use it in GitHub Desktop.
Django template tag for encoding images in base64 and rendering with server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+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!