Skip to content

Instantly share code, notes, and snippets.

@Genarito
Last active January 3, 2024 14:37
Show Gist options
  • Save Genarito/208164e1da82f0fd08e62cbac31e79f6 to your computer and use it in GitHub Desktop.
Save Genarito/208164e1da82f0fd08e62cbac31e79f6 to your computer and use it in GitHub Desktop.
Django template tag for encoding images in base64 and rendering with server with Python 3.x
from django import template
from django.contrib.staticfiles.finders import find as find_static_file
import base64
register = template.Library()
def get_file_data(file_path: str) -> bytes:
"""
@param file_path: Path of the file to get the data
"""
with open(file_path, 'rb') as f:
data = f.read()
f.close()
return data
@register.simple_tag
def encode_static_base_64(path: str) -> str:
"""
A template tag that returns an encoded string representation of a static file
Usage::
{% encode_static_base_64 path [encoding] %}
Examples::
<img src="{% encode_static_base_64 'path/to/img.png' %}">
"""
try:
file_path = find_static_file(path)
if file_path is None:
return ''
ext = file_path.split('.')[-1]
file_str = base64.b64encode(get_file_data(file_path)).decode('utf-8')
return f"data:image/{ext};base64,{file_str}"
except IOError:
return ''
@AllenEllis
Copy link

If the file doesn't exist, this will crash and prevent the template from rendering. I fixed that by catching it here:

        try:
            ext = file_path.split(".")[-1]
        except AttributeError:
            return ""

@Genarito
Copy link
Author

Genarito commented Jun 13, 2022

You're right @AllenEllis! I've updated the script to check if it's None. Thank you!

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