Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Created February 26, 2025 15:30
Show Gist options
  • Save mariocesar/ef82ee290f22e4ce65931a37b9c56dd7 to your computer and use it in GitHub Desktop.
Save mariocesar/ef82ee290f22e4ce65931a37b9c56dd7 to your computer and use it in GitHub Desktop.
A django template tag that generates SVG icons. Useful to create svg favicons with emojis

Usage

{% load utils_tags %}
{% svgicon '🕶️' 'rounded square' '#ffccff' as icon %}
<link rel="icon" href="data:image/svg+xml,{{ icon | urlencode }}">

Will make a nice favicon of sunglases with a pink background.

Test the following to see what it can do

{% svgicon '🕶️' %}
{% svgicon '🕶️' 'circle' %}
{% svgicon '🕶️' 'circle' '#ffccff' %}
import html
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def svgicon(text, shape=None, bg_color=None):
"""Generates an SVG icon with the given text/emoji and optional background shape and color."""
if shape and not bg_color:
bg_color = "white"
safe_text = html.escape(text)
svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="1em" height="1em">'
match shape:
case "square":
svg += f'<rect x="0" y="0" width="100" height="100" fill="{bg_color}" />'
case "rounded square":
svg += f'<rect x="0" y="0" width="100" height="100" rx="15" ry="15" fill="{bg_color}" />'
case "circle":
svg += f'<circle cx="50" cy="50" r="50" fill="{bg_color}" />'
svg += '<text x="50" y="50" dominant-baseline="central" text-anchor="middle" font-size="60" font-family="sans-serif">'
svg += safe_text
svg += "</text>"
svg += "</svg>"
return mark_safe(svg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment