# Custom template tag for Django to return link tag if target path is not current, and text if is.
# Writing custom template tags:
# https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#writing-custom-template-tags
from django.template import Library
from django.urls import reverse
from django.utils.html import format_html, mark_safe
import re
register = Library()
@register.simple_tag(takes_context=True)
def link_unless_curent(context, path_name, link_text=''):
"""
(Link should not target current page, in terms of UX)
Returns link tag if target path is not current.
Highlightes if target is parent of current.
"""
current_path = context['request'].path
target_path = reverse(path_name)
if link_text == '':
link_text = path_name.capitalize()
response = '{}'
if current_path == target_path:
# is current
response = format_html(
'{}',
link_text,
)
elif re.match(target_path, current_path):
# is parent of current
response = format_html(
response,
target_path,
mark_safe(f'{link_text}'),
)
else:
# not related to current
response = format_html(
response,
target_path,
link_text,
)
return response