# Imports
from django.urls import reverse
# Exports
__all__ = (
"Breadcrumb",
"Breadcrumbs",
)
# Classes
[docs]class Breadcrumb(object):
"""Helper class that ensures an object has the required attributes."""
[docs] def __init__(self, text, url):
"""Initialize the crumb.
:param text: The text of the link.
:type text: str
:param url: The URL of the link.
:type url: str
"""
self.text = text
self.url = url
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.text)
[docs] def get_absolute_url(self):
"""Allow the crumb to simulate a model with ``get_absolute_url()``.
:rtype: str
"""
return self.url
[docs]class Breadcrumbs(object):
"""Collect objects to be displayed as breadcrumbs."""
[docs] def __init__(self):
"""Initialize the ``items`` attribute for a new collection of crumbs."""
self.items = list()
def __iter__(self):
return iter(self.items)
[docs] def add(self, text, url, pattern_args=None, pattern_kwargs=None, namespace=None):
"""Add a breadcrumb to the list.
:param text: The breadcrumb label/text.
:type text: str
:param url: The URL or pattern name.
:type url: str
:param pattern_args: Pattern arguments when the URL is given as a pattern name.
:type pattern_args: list
:param pattern_kwargs: Pattern keyword arguments when the URL is given as a pattern name.
:type pattern_kwargs: dict
:param namespace: The application namespace for the URL when given as a pattern name.
:type namespace: str
:rtype: Breadcrumb
"""
if pattern_args or pattern_kwargs:
if namespace is not None:
_url = "%s:%s" % (namespace, url)
else:
_url = url
resolved_url = reverse(_url, args=pattern_args, kwargs=pattern_kwargs)
else:
resolved_url = url
breadcrumb = Breadcrumb(text, resolved_url)
self.items.append(breadcrumb)
return breadcrumb
[docs] def insert(self, index, text, url, pattern_args=None, pattern_kwargs=None, namespace=None):
"""Insert a breadcrumb in the list.
:param index: The index of the new breadcrumb..
:type index: int
:param text: The breadcrumb label/text.
:type text: str
:param url: The URL or pattern name.
:type url: str
:param pattern_args: Pattern arguments when the URL is given as a pattern name.
:type pattern_args: list
:param pattern_kwargs: Pattern keyword arguments when the URL is given as a pattern name.
:type pattern_kwargs: dict
:param namespace: The application namespace for the URL when given as a pattern name.
:type namespace: str
:rtype: Breadcrumb
"""
if pattern_args or pattern_kwargs:
if namespace is not None:
_url = "%s:%s" % (namespace, url)
else:
_url = url
resolved_url = reverse(_url, args=pattern_args, kwargs=pattern_kwargs)
else:
resolved_url = url
breadcrumb = Breadcrumb(text, resolved_url)
self.items.insert(index, breadcrumb)
return breadcrumb