Created
June 13, 2020 19:31
-
-
Save efojs/18e89bec1df98a7462bf337b65450baa to your computer and use it in GitHub Desktop.
Custom template tag for Django to return link tag, if target path is not current, and text if it is
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Writing custom template tags: | |
# https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#writing-custom-template-tags | |
# | |
# Usage: | |
# {% link_unless_current 'target_path_name' 'optional_link_text' %} | |
# returns | |
# if not current: <a href="{ reverse(target_path_name) }">{ link_text }</a> | |
# if current: <strong>{ link_text }</strong> | |
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_current(context, target_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(target_path_name) | |
if link_text == '': | |
link_text = target_path_name.capitalize() | |
response = '<a href="{}">{}</a>' | |
if current_path == target_path: | |
# is current | |
response = format_html( | |
'<strong>{}</strong>', | |
link_text, | |
) | |
elif re.match(target_path, current_path): | |
# is parent of current | |
response = format_html( | |
response, | |
target_path, | |
mark_safe(f'<strong>{link_text}</strong>'), | |
) | |
else: | |
# not related to current | |
response = format_html( | |
response, | |
target_path, | |
link_text, | |
) | |
return response | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment