Skip to content

Commit

Permalink
Add ability to add arbitrary HTML attributes to SVG icons
Browse files Browse the repository at this point in the history
To play nicer with assistive technologies, we sometimes need to add ARIA
attributes to our SVG icons, e.g. `aria-hidden=true`.

See cfpb/design-system#1965
  • Loading branch information
contolini committed Apr 26, 2024
1 parent 230d3bf commit c623fba
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
11 changes: 7 additions & 4 deletions cfgov/core/templatetags/svg_icon.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
)


def load_svg(name: str) -> str:
def load_svg(name: str, attrs: dict) -> str:
relative_path = f"icons/{name}.svg"
if not (static_filename := finders.find(relative_path)):
raise FileNotFoundError(f"{relative_path} not found in staticfiles.")
Expand All @@ -32,15 +32,18 @@ def load_svg(name: str) -> str:
content = f.read()
if not SVG_REGEX.match(content):
raise ValueError(f"{static_filename} not a valid SVG.")
if attrs:
attrs = " ".join([f"{key}='{value}'" for key, value in attrs.items()])
content = content.replace("<svg", f"<svg {attrs}")
return content


@register.simple_tag()
def svg_icon(name: str) -> SafeString:
def svg_icon(name: str, attrs: dict = {}) -> SafeString:
"""Return SVG content given an icon name."""
try:
content = load_svg(name)
content = load_svg(name, attrs)
except (FileNotFoundError, ValueError) as e:
logger.warning(f"{e} Substituting with {FALLBACK_ICON_NAME}.svg!")
content = load_svg(FALLBACK_ICON_NAME)
content = load_svg(FALLBACK_ICON_NAME, attrs)
return mark_safe(content)
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
========================================================================== #}
<div class="m-contact m-contact-hyperlink">
<span class="h5">
{{ svg_icon('web') }}
{{ svg_icon('web', {'aria-hidden': 'true'}) }}
Web
</span>
<p>
Expand Down

0 comments on commit c623fba

Please sign in to comment.