Skip to content

Commit

Permalink
refactor: inline _bs_icon
Browse files Browse the repository at this point in the history
`_bs_icon` is only called in `icon`, so there is no reason for it to be a
separate function. Additionally, by moving it to `icon`, we can ensure that only
whitelisted icon names are used, reducing the chance of actual string injection
attacks.
  • Loading branch information
Restioson committed Nov 7, 2024
1 parent 4410af2 commit ad052ba
Showing 1 changed file with 11 additions and 17 deletions.
28 changes: 11 additions & 17 deletions app/general/templatetags/bs_icons.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import re

from django import template
from django.utils.safestring import mark_safe

Expand All @@ -12,20 +10,6 @@


register = template.Library()
icon_name_re = re.compile(r"[a-z0-9\-]+")


def _bs_icon(name):
assert icon_name_re.fullmatch(name)
return mark_safe(f'<i aria-hidden="true" class="icon bi-{name}"></i> ')
# The trailing space is intentional: Since this is an inline element
# usually followed by text, the absence/presence of a space is significant,
# and usually wanted for layout. That's too hard to remember, so we always
# add it. Multiple spaces are equal to one. That way the exact layout of
# code in the templates doesn't matter. Beware of using {% spaceless %}
# which will negate this. A pure CSS solution escaped me thus far, since a
# space will take additional space in addition to a margin.


# a mapping from project types to Bootstrap icon names:
_icons = {
Expand All @@ -44,4 +28,14 @@ def icon(name):
if not (bs_name := _icons.get(name)):
raise template.TemplateSyntaxError(f"'icon' requires a registered icon name (got {name!r})")

return _bs_icon(bs_name)
# This `mark_safe` is okay because we only allow certain, whitelisted strings. This is enforced above by fetching it
# from the `_icons` dictionary
return mark_safe(f'<i aria-hidden="true" class="icon bi-{bs_name}"></i> ') # noqa: S308 - see above

# The trailing space is intentional: Since this is an inline element
# usually followed by text, the absence/presence of a space is significant,
# and usually wanted for layout. That's too hard to remember, so we always
# add it. Multiple spaces are equal to one. That way the exact layout of
# code in the templates doesn't matter. Beware of using {% spaceless %}
# which will negate this. A pure CSS solution escaped me thus far, since a
# space will take additional space in addition to a margin.

0 comments on commit ad052ba

Please sign in to comment.