Skip to content

Commit 9fd954f

Browse files
committed
feat(templatetags): custom svg tag to replace django-inline-svg
1 parent 60adc15 commit 9fd954f

File tree

4 files changed

+56
-2
lines changed

4 files changed

+56
-2
lines changed

docs/source/reference_index/apps/templatetags.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ templatetags
1616
paginate
1717
status_helper
1818
strings
19+
svg
1920
tests

intranet/apps/templatetags/svg.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import logging
2+
import os
3+
4+
from django import template
5+
from django.contrib.staticfiles import finders
6+
from django.core.exceptions import ImproperlyConfigured
7+
from django.utils.safestring import mark_safe
8+
9+
from intranet import settings
10+
11+
logger = logging.getLogger(__name__)
12+
register = template.Library()
13+
14+
# An updated version of django-inline-svg that works with django 5+
15+
16+
17+
class SVGNotFound(FileNotFoundError):
18+
pass
19+
20+
21+
@register.simple_tag
22+
def svg(filename):
23+
SVG_DIRS = getattr(settings, "SVG_DIRS", [])
24+
25+
if not isinstance(SVG_DIRS, list):
26+
raise ImproperlyConfigured("SVG_DIRS setting must be a list")
27+
28+
path = None
29+
30+
if SVG_DIRS:
31+
for directory in SVG_DIRS:
32+
svg_path = os.path.join(directory, "%s.svg" % filename)
33+
if os.path.isfile(svg_path):
34+
path = svg_path
35+
else:
36+
path = finders.find(os.path.join("svg", "%s.svg" % filename))
37+
38+
if not path:
39+
message = "SVG '%s.svg' not found" % filename
40+
41+
# Raise exception if DEBUG is True, else just log a warning.
42+
if settings.DEBUG:
43+
raise SVGNotFound(message)
44+
else:
45+
logger.warning(message)
46+
return ""
47+
48+
# Sometimes path can be a list/tuple if there's more than one file found
49+
if isinstance(path, list | tuple):
50+
path = path[0]
51+
52+
with open(path) as svg_file:
53+
svg = mark_safe(svg_file.read())
54+
55+
return svg

intranet/settings/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -697,7 +697,6 @@ def get_month_seconds():
697697
"oauth2_provider", # django-oauth-toolkit
698698
"corsheaders", # django-cors-headers
699699
"cacheops", # django-cacheops
700-
"svg", # django-inline-svg
701700
"simple_history", # django-simple-history
702701
"django_referrer_policy",
703702
"django_user_agents",

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ django-cors-headers==4.7.0
1111
django-debug-toolbar==5.2.0
1212
django-extensions==4.1
1313
django-formtools==2.5.1
14-
django-inline-svg==0.1.1
1514
django-maintenance-mode==0.22.0
1615
django-oauth-toolkit==3.0.1
1716
django-pipeline==4.0.0

0 commit comments

Comments
 (0)