This commit is contained in:
Abhimanyu Saharan 2023-11-08 22:08:56 +05:30
parent 8b1e18502f
commit 28fc6555ef

View File

@ -3,48 +3,35 @@ from django.utils.safestring import mark_safe
register = template.Library()
def _display_site(obj):
"""
Render a link to the site of an object.
"""
if hasattr(obj, 'site'):
return mark_safe('<a href="{}">{}</a>'.format(
obj.site.get_absolute_url(),
obj.site
))
return None
site = getattr(obj, 'site', None)
return mark_safe('<a href="{}">{}</a>'.format(site.get_absolute_url(), site)) if site else None
@register.simple_tag(takes_context=True)
def display_region(context, obj, include_site=False):
"""
Renders hierarchical region data for a given object.
Renders hierarchical region data for a given object, optionally including the site.
"""
# Attempt to retrieve the region from obj or its site attribute
region = getattr(obj, 'region', None) or getattr(getattr(obj, 'site', None), 'region', None)
# Retrieve the region or site information
region = getattr(obj, 'region', None) or getattr(obj.site, 'region', None) if hasattr(obj, 'site') else None
site_link = _display_site(obj) if include_site else None
# Return a placeholder if no region is found
if not region:
# If include_site is True, attempt to retrieve the site from obj
if include_site:
return _display_site(obj) or mark_safe('&mdash;')
# Return a placeholder if no region or site is found
if not region and not site_link:
return mark_safe('&mdash;')
# Retrieve all regions in the hierarchy
regions = region.get_ancestors(include_self=True)
# Build the region links if the region is available
region_links = ' / '.join(
'<a href="{}">{}</a>'.format(context['request'].build_absolute_uri(reg.get_absolute_url()), reg)
for reg in region.get_ancestors(include_self=True)
) if region else ''
# Build the URLs and names for the regions
regions_links = [
'<a href="{}">{}</a>'.format(
context['request'].build_absolute_uri(region.get_absolute_url()), region
) for region in regions
]
# Concatenate region and site links
links = ' / '.join(filter(None, [region_links, site_link]))
# Render the hierarchy as a list of links
region = mark_safe(' / '.join(regions_links))
if include_site:
site = _display_site(obj)
if site:
return mark_safe('{} / {}'.format(region, site))
return region
return mark_safe(links)