Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 30 additions & 14 deletions src/lucide/templatetags/lucide.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,41 @@
from __future__ import annotations

from django import template
from django.utils.safestring import SafeString
from django.utils.safestring import mark_safe
from django.template import Context, Template, TemplateSyntaxError
from django.utils.safestring import SafeString, mark_safe

import lucide as _lucide

register = template.Library()


@register.simple_tag
def lucide(name: str, *, size: int | None = 24, **kwargs: object) -> str:
return _render_icon(name, size, **kwargs)
@register.simple_tag(takes_context=True) # Added takes_context=True
def lucide(context: Context, name: str, *, size: int | None = 24, **kwargs: object) -> str:
return _render_icon(context, name, size, **kwargs) # Pass context


def _render_icon(name: str, size: int | None, **kwargs: object) -> str:
# simple_tag's parsing loads passed strings as safe, but they aren't
# Cast the SafeString's back to normal strings the only way possible, by
# concatenating the empty string.
fixed_kwargs = {
key: (value + "" if isinstance(value, SafeString) else value)
for key, value in kwargs.items()
}
return mark_safe(_lucide._render_icon(name, size, **fixed_kwargs))
def _render_icon(context: Context, name: str, size: int | None, **kwargs: object) -> str:
processed_kwargs = {}
for key, value in kwargs.items():
# Original SafeString to str conversion logic
value_to_process = value + "" if isinstance(value, SafeString) else value

if isinstance(value_to_process, str) and \
("{" in value_to_process and ("{{" in value_to_process or "{%" in value_to_process)):
# If the string value appears to contain Django template syntax,
# try to render it using the current template context.
try:
# Create a Template object from the attribute value and render it
attr_template = Template(value_to_process)
processed_kwargs[key] = attr_template.render(context)
except TemplateSyntaxError:
# In case of a syntax error within the attribute's template string,
# fall back to using the original (un-rendered) string.
# This prevents breaking templates with unintentional or malformed template syntax in attributes.
processed_kwargs[key] = value_to_process
else:
# Value is not a string or does not appear to contain template syntax.
# Use it as is (after SafeString conversion if applicable).
processed_kwargs[key] = value_to_process

return mark_safe(_lucide._render_icon(name, size, **processed_kwargs))