Advertisement
Guest User

link_unless_curent

a guest
Jun 13th, 2020
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. # Custom template tag for Django to return link tag if target path is not current, and text if is.
  2. # Writing custom template tags:
  3. # https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#writing-custom-template-tags
  4.  
  5. from django.template import Library
  6. from django.urls import reverse
  7. from django.utils.html import format_html, mark_safe
  8. import re
  9.  
  10. register = Library()
  11.  
  12. @register.simple_tag(takes_context=True)
  13. def link_unless_curent(context, path_name, link_text=''):
  14.     """
  15.    (Link should not target current page, in terms of UX)
  16.    Returns link tag if target path is not current.
  17.    Highlightes if target is parent of current.
  18.    """
  19.     current_path = context['request'].path
  20.     target_path = reverse(path_name)
  21.  
  22.     if link_text == '':
  23.         link_text = path_name.capitalize()
  24.  
  25.     response = '<a href="{}">{}</a>'
  26.  
  27.     if current_path == target_path:
  28.         # is current
  29.         response = format_html(
  30.             '<strong>{}</strong>',
  31.             link_text,
  32.         )
  33.     elif re.match(target_path, current_path):
  34.         # is parent of current
  35.         response = format_html(
  36.             response,
  37.             target_path,
  38.             mark_safe(f'<strong>{link_text}</strong>'),
  39.         )
  40.     else:
  41.         # not related to current
  42.         response = format_html(
  43.             response,
  44.             target_path,
  45.             link_text,
  46.         )
  47.  
  48.     return response
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement