Adding inline_svg django tag

This commit is contained in:
Michael Bergbauer 2025-06-14 15:48:46 +02:00
parent fe3c3cea16
commit 6ea6cd7132
2 changed files with 22 additions and 0 deletions

View File

View File

@ -0,0 +1,22 @@
# common/templatetags/svg.py
from django import template
from django.utils.safestring import mark_safe
from django.contrib.staticfiles import finders
import re
register = template.Library()
@register.simple_tag
def inline_svg(path, css_class='', style=''):
svg_file_path = finders.find(path)
if not svg_file_path:
return f"<!-- SVG '{path}' not found -->"
with open(svg_file_path, 'r', encoding='utf-8') as file:
svg_content=mark_safe(file.read())
if css_class:
svg_content = re.sub(r'<svg([^>]+)?', rf'<svg\1 class="{css_class}"', svg_content, count=1)
if style:
svg_content = re.sub(r'<svg([^>]+)?', rf'<svg\1 style="{style}"', svg_content, count=1)
return mark_safe(svg_content)