Navigation#
- class BasicMenu(*args: Any, **kwargs: Any)[source]#
Bases:
WidgetInitKwargsMixinBasic menu widget.
A basic menu requires only one class attribute defined,
items.Example
from wildewidgets import BasicMenu class MainMenu(BasicMenu): items = [ ('Users', 'core:home'), ('Uploads','core:uploads'), ]
- add_menu_item(title: str, data: dict[str, Any], active: bool = False) → None[source]#
Add a menu item to the menu structure.
This method adds a new item to the menu with the specified title and data, and optionally marks it as the active item.
- Parameters:
title – The text to display for the menu item
data – Dictionary containing the item’s configuration (url, kind, etc.)
- Keyword Arguments:
active – Whether this item should be marked as active
- build_menu() → None[source]#
Build the menu structure based on the active hierarchy.
This method processes the items defined in the class attribute and creates a structured representation of the menu. It handles both regular menu items and submenus, and marks the appropriate items as active based on the active_hierarchy.
The method:
Processes each item in the items list
Creates appropriate data structures for regular items and submenus
Marks items as active if they match the active_hierarchy
Adds query parameters if specified in the item definition
Note
This method is called automatically by get_content() and doesn’t need to be called directly.
- get_content(**kwargs: Any) → str[source]#
Render the menu as HTML content.
This method:
Builds the menu structure
Creates a context dictionary with all necessary data
Renders the template with the context
- Keyword Arguments:
**kwargs – Additional arguments (unused)
- Returns:
The rendered HTML content for the menu
- Return type:
- parse_submemu(items: list[tuple[str, str | None]], submenu_active: str | None) → dict[str, Any][source]#
Parse and create a submenu structure.
This method processes a list of submenu items and creates a structured representation of the submenu. It handles regular items and dividers, and marks the appropriate item as active based on the submenu_active parameter.
- Parameters:
items – List of tuples defining submenu items (title, url, [extra])
- Keyword Arguments:
submenu_active – The name of the submenu item to mark as active
- Returns:
A dictionary containing the structured submenu data
- Return type:
- brand_image: str | None = None#
The image to use for the brand logo. If this is set, the brand text will not be displayed. If you want to use a brand text, set this to
None. The image should be a URL or a static file path.
- brand_image_width: str = '100%'#
The CSS width to use for the brand image. This is only used if
brand_imageis set. If you want the image to be responsive, set this to100%.
- brand_url: str = '#'#
The URL to use for the brand link. If this is set, the brand image or text will be used as the link.
- items: ClassVar[list[tuple[str, str | list[tuple[str, str | None]] | dict[str, str] | None]]] = []#
A list of tuples that define the items to list in the menu, where the first element is the menu item text and the second element is the URL name. A third optional element in the tuple can be a dictionary of get arguments
- class DarkMenu(*args: Any, **kwargs: Any)[source]#
Bases:
BasicMenuA dark-themed navigation menu.
This class extends the BasicMenu with dark styling using Bootstrap’s dark navbar classes. It provides a dark background with light text, suitable for applications with darker themes.
Example
from wildewidgets import DarkMenu class MainDarkMenu(DarkMenu): items = [ ('Dashboard', 'dashboard'), ('Reports', 'reports'), ]
- class LightMenu(*args: Any, **kwargs: Any)[source]#
Bases:
BasicMenuA light-themed navigation menu.
This class extends the BasicMenu with light styling, which is also the default for BasicMenu. It provides a light background with dark text, suitable for standard application layouts.
Example
from wildewidgets import LightMenu class MainLightMenu(LightMenu): items = [ ('Home', 'home'), ('About', 'about'), ('Contact', 'contact'), ]
- class MenuMixin[source]#
Bases:
objectA mixin for adding menu support to Django class-based views.
This mixin provides methods for including primary and secondary navigation menus in Django views. It automatically adds menu instances to the template context, making it easy to integrate navigation in templates.
To use this mixin:
Define menu classes by subclassing
BasicMenuor its variantsAdd this mixin to your view classes
Set class attributes to specify which menus to use and which items to activate
You must define the
menu_classand themenu_item, butsubmenu_classand thesubmenu_itemare optional. If you do not set them, no secondary menu will be displayed.Example
With no secondary menu:
from django.views.generic import TemplateView from wildewidgets import BasicMenu, MenuMixin class MainMenu(BasicMenu): items = [ ('Home', 'home'), ('About', 'about'), ('Contact', 'contact'), ] class DashboardView(MenuMixin, TemplateView): template_name = "dashboard.html" menu_class = MainMenu menu_item = "Home"
With a secondary menu:
from django.views.generic import TemplateView from wildewidgets import BasicMenu, LightMenu, MenuMixin class MainMenu(BasicMenu): items = [ ('Home', 'home'), ('About', 'about'), ('Contact', 'contact'), ] class DashboardSubmenu(LightMenu): items = [ ('Overview', 'dashboard:overview'), ('Statistics', 'dashboard:statistics'), ('Settings', 'dashboard:settings'), ] class DashboardView(MenuMixin, TemplateView): template_name = "dashboard.html" menu_class = MainMenu menu_item = "Home" submenu_class = DashboardSubmenu submenu_item = "Overview"
- get_context_data(**kwargs: Any) → dict[str, Any][source]#
Add menu instances to the template context.
This method adds the primary and secondary menu instances to the context if they are available.
- Parameters:
**kwargs – Additional context variables
- Returns:
The updated template context with menu instances
- get_menu() → wildewidgets.menus.BasicMenu | None[source]#
Get an instance of the primary menu.
This method instantiates the menu class with the active item.
- Returns:
An instance of the menu, or None if no menu class is specified
- get_menu_class() → type[wildewidgets.menus.BasicMenu] | None[source]#
Get the class to use for the primary menu.
This method returns the menu_class attribute by default, but can be overridden to provide dynamic menu class selection.
- Returns:
The menu class to use, or None if no menu should be displayed
- get_menu_item() → str | None[source]#
Get the active item for the primary menu.
This method returns the menu_item attribute by default, but can be overridden to provide dynamic active item selection.
- Returns:
The name of the menu item to mark as active, or None if no item should be active
- get_submenu() → wildewidgets.menus.BasicMenu | None[source]#
Get an instance of the secondary menu.
This method instantiates the submenu class with the active item.
- Returns:
An instance of the submenu, or None if no submenu class is specified
- get_submenu_class() → type[wildewidgets.menus.BasicMenu] | None[source]#
Get the class to use for the secondary menu.
This method returns the submenu_class attribute by default, but can be overridden to provide dynamic submenu class selection.
- Returns:
The submenu class to use, or None if no submenu should be displayed
- get_submenu_item() → str | None[source]#
Get the active item for the secondary menu.
This method returns the submenu_item attribute by default, but can be overridden to provide dynamic active item selection.
- Returns:
The name of the submenu item to mark as active, or None if no item should be active
- menu_class: type[wildewidgets.menus.BasicMenu] | None = None#
The primary menu class to use for the view. This should be a subclass of BasicMenu or one of its variants. If set to None, no primary menu will be displayed.
- submenu_class: type[wildewidgets.menus.BasicMenu] | None = None#
The secondary menu class to use for the view.
- class VerticalDarkMenu(*args: Any, **kwargs: Any)[source]#
Bases:
BasicMenuA vertical dark-themed navigation menu.
This class extends the BasicMenu with dark styling and vertical orientation. It’s particularly useful for sidebar navigation in applications with darker themes.
Example
from wildewidgets import VerticalDarkMenu class SidebarMenu(VerticalDarkMenu): items = [ ('Profile', 'user_profile'), ('Settings', 'user_settings'), ('Logout', 'logout'), ]
- class BreadcrumbBlock(*args, title_class: str | None = None, **kwargs)[source]#
Bases:
BlockA Bootstrap breadcrumb navigation component.
This widget creates a breadcrumb trail showing the hierarchical path to the current page. It’s typically used to show navigation context and allow users to navigate back up the hierarchy.
You can create a base BreadcrumbBlock with common starting points (like ‘Home’) and then extend it in specific views to add additional breadcrumbs for deeper pages.
- items#
Base list of breadcrumb items to always include
- breadcrumbs#
The OrderedList that holds the actual breadcrumb items
Examples
Creating a base breadcrumb class:
from wildewidgets import BreadcrumbBlock class BaseBreadcrumbs(BreadcrumbBlock): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.add_breadcrumb('Home', url='/home')
Using breadcrumbs in a view:
def get_context_data(self, **kwargs): kwargs = super().get_context_data(**kwargs) breadcrumbs = BaseBreadcrumbs() breadcrumbs.add_breadcrumb('Products', url='/products') breadcrumbs.add_breadcrumb('Product Detail') kwargs['breadcrumbs'] = breadcrumbs return kwargs
- add_breadcrumb(title: str, url: str | None = None) → None[source]#
Add a new breadcrumb item to the breadcrumb trail.
This method appends a new item to the end of the breadcrumb list. The last item added will be styled as the active/current item.
- Parameters:
title – Display text for the breadcrumb
url – Optional URL for the breadcrumb link. If None, the item will be displayed as plain text (typically for the current page).
Examples
… code-block:: python
from wildewidgets import BreadcrumbBlock
breadcrumbs = BreadcrumbBlock() breadcrumbs.add_breadcrumb(‘Home’, url=’/home’) breadcrumbs.add_breadcrumb(‘Products’, url=’/products’) breadcrumbs.add_breadcrumb(‘Product Detail’) # Current page has no URL
- flatten() → str[source]#
Convert all breadcrumb items to a single string.
This method joins all breadcrumb titles with a separator, which is useful for creating page titles or meta descriptions that include the full navigation path.
- Returns:
All breadcrumb titles joined with “ - “
- Return type:
Examples
… code-block:: python
from wildewidgets import BreadcrumbBlock
breadcrumbs = BreadcrumbBlock() breadcrumbs.add_breadcrumb(‘Home’) breadcrumbs.add_breadcrumb(‘Products’) breadcrumbs.add_breadcrumb(‘Product Detail’) print(breadcrumbs.flatten()) # this will print: ‘Home - Products - Product Detail’
- get_context_data(*args, **kwargs) → dict[str, Any][source]#
Prepare the context data for template rendering.
This method builds the actual breadcrumb HTML elements from the stored breadcrumb items, adding the appropriate classes and marking the last item as active.
- Parameters:
*args – Positional arguments passed to parent method
**kwargs – Keyword arguments passed to parent method
- Returns:
Updated context dictionary with breadcrumb-specific data
- Return type:
- aria_attributes: dict[str, str] = {'label': 'breadcrumb'}#
Additional
aria-attributes to set on this block
- breadcrumbs#
The
<ol>that holds our breadcrumbs
- items: list[BreadcrumbItem] = []#
The list of
BreadcrumbItemobjects from which we will build our breadcrumb HTML
- class BreadcrumbItem(title: str, url: str | None = None)[source]#
Bases:
objectA single item in a breadcrumb navigation trail.
This dataclass represents one segment in a breadcrumb navigation component, containing a title and an optional URL. Items without URLs typically represent the current page.
- url#
Optional URL the breadcrumb item should link to. If None, the item will be displayed as plain text (typically the current page).
- Type:
str | None
Examples
>>> home = BreadcrumbItem(title="Home", url="/") >>> section = BreadcrumbItem(title="Products", url="/products/") >>> current = BreadcrumbItem(title="Product Details")
- class ClickableNavDropdownControl(menu_id: str, text: str | None = None, icon: str | wildewidgets.widgets.icons.TablerMenuIcon | None = None, url: str | None = None, active: bool = False, **kwargs)[source]#
Bases:
BlockA control for dropdown menus with a separate clickable link.
This specialized control provides both a clickable link and a dropdown toggle in one component. It allows the user to either navigate to a URL by clicking the main text, or open a dropdown menu by clicking a separate arrow.
- icon#
Optional icon to display
- Type:
- link#
The Link object for the clickable text
- control#
The Link object that toggles the dropdown
Examples
Basic usage:
… code-block:: python
from wildewidgets import ClickableNavDropdownControl
- control = ClickableNavDropdownControl(
‘dropdown-menu-id’, text=’Products’, url=’/products’
)
With an icon:
… code-block:: python
from wildewidgets import ClickableNavDropdownControl
- control = ClickableNavDropdownControl(
‘dropdown-menu-id’, text=’Products’, url=’/products’, icon=’box’
)
)
- Parameters:
menu_id – CSS ID of the dropdown menu to control
- Keyword Arguments:
text – The text to display as the link
icon – Optional icon to display
url – The URL to navigate to when clicking the text
active – Whether this item should be highlighted as active
**kwargs – Additional keyword arguments passed to parent Block class
- Raises:
ValueError – If no URL is provided
ValueError – If no text is provided
- collapse() → None[source]#
Set the dropdown to collapsed state.
This updates the aria-expanded attribute to ‘false’ to indicate that the associated dropdown menu is closed.
- expand() → None[source]#
Set the dropdown to expanded state.
This updates the aria-expanded attribute to ‘true’ to indicate that the associated dropdown menu is open.
- active: bool#
If this is
True, this control itself is active, but nothing in the relatedDropdownMenuis
- block: str = 'nav-item--clickable'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- icon: str | TablerMenuIcon | None = None#
Either the name of a Bootstrap icon, or a
TablerMenuIconclass or subclass
- class DropdownItem(text: str | None = None, icon: str | None = None, active: bool = False, item: wildewidgets.widgets.navigation.MenuItem | None = None, **kwargs)[source]#
Bases:
LinkAn item within a dropdown menu.
This widget creates a link styled for use within dropdown menus. It can include an optional icon and handles active state.
- icon#
Optional icon to display
- Type:
Examples
With no icon:
from wildewidgets import DropdownItem item = DropdownItem( text='Edit Profile', url='/profile/edit' )
With an icon:
… code-block:: python
from wildewidgets import DropdownItem
- item = DropdownItem(
text=’Settings’, url=’/settings’, icon=’gear’
)
- Keyword Arguments:
text – The text to display
icon – Optional icon to display
active – Whether this item should be highlighted as active
item – A MenuItem object to create this DropdownItem from
**kwargs – Additional keyword arguments passed to parent Link class
- Raises:
ValueError – If both item and other parameters are provided
ValueError – If no text is provided
ValueError – If no URL is provided
- block: str = 'dropdown-item'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- icon: str | TablerMenuIcon | None = None#
this is either the name of a bootstrap icon, or a
TablerMenuIconclass or subclass
- class DropdownMenu(*items: MenuItem, button_id: str | None = None, **kwargs)[source]#
Bases:
BlockTypically, you won’t use this directly, but instead it will be created for you from a
MenuItemspecification whenMenuItem.urlis notNone.Examples
… code-block:: python
from wildewidgets import DropdownMenu, MenuItem, NavDropdownControl
- items = [
MenuItem(text=’One’, url=’/one’, icon=’1-circle’), MenuItem(text=’Two’, url=’/two’, icon=’2-circle’), MenuItem(text=’Three’, url=’/three’, icon=’3-circle’),
] button = NavDropdownControl(
text=’My Dropdown Menu’, icon=’arrow-down-square-fill’, button_id=’my-button’
) menu = DropdownMenu(*items, button_id=button.button_id)
- Parameters:
*items – the list of
MenuItemobjects to insert into this menu- Keyword Arguments:
button_id – it CSS id for the button
- Raises:
ValueError – one or more of the settings failed validation
- add_item(text: str | None = None, url: str | None = None, icon: str | wildewidgets.widgets.icons.TablerMenuIcon | None = None, active: bool = False, item: wildewidgets.widgets.navigation.MenuItem | None = None) → None[source]#
Add a new item to this
DropdownMenu.- Keyword Arguments:
icon – Either the name of a Bootstrap icon, or a
TablerMenuIconobjecttext – The text for the item
url – The URL for the item
active –
Trueif this represents the page we’re currently onitem – a
MenuItem
- Raises:
ValueError – one or more of the settings failed validation
- class Menu(*items: MenuItem, title: str | None = None, title_tag: str | None = None, title_css_classes: str | None = None, **kwargs)[source]#
Bases:
BlockA
<div>with an optional title and a Bootstrap ``ul.navbar-nav` <https://getbootstrap.com/docs/5.2/components/navbar/>`_ for use in aNavbar.Use this in any of these ways:
Pass in the
itemskwargs to the constructorAdd items with
add_itemSubclass
Menu, defineitems, and add additional items withadd_item
Examples
Subclassing:
from wildewidgets import Menu, MenuItem class MyMenu(Menu): items = [ MenuItem(text='One', url='/one', icon='1-circle'), MenuItem(text='Two', url='/two', icon='2-circle'), MenuItem(text='Three', url='/three', icon='3-circle'), ]
Constructor:
from wildewidgets import Menu, MenuItem menu = Menu( MenuItem(text='One', url='/one', icon='1-circle'), MenuItem(text='Two', url='/two', icon='2-circle'), MenuItem(text='Three', url='/three', icon='3-circle'), )
Menu.add_item:from wildewidgets import Menu, MenuItem menu = Menu() menu.add_item(MenuItem(text='One', url='/one', icon='1-circle')) menu.add_item(MenuItem(text='Two', url='/two', icon='2-circle')) menu.add_item(MenuItem(text='Three', url='/three', icon='3-circle'))
- Parameters:
*items – the list of
MenuItemobjects to insert into this menu- Keyword Arguments:
title – the title for this menu
title_tag – the HTML tag to use for the title
title_css_classes – CSS classes to apply to the title
- Raises:
ValueError – one or more of the settings failed validation
- activate(text: str) → bool[source]#
Activate the menu item matching the given text or URL.
This method searches through all menu items (including nested items in dropdowns) and sets the first matching item to active. This is useful for highlighting the current page in the navigation.
- Parameters:
text – Text or URL to match against menu items
- Returns:
True if a matching item was found and activated
- Return type:
Examples
>>> menu = Menu( ... MenuItem(text='Home', url='/'), ... MenuItem(text='Products', url='/products/') ... ) >>> menu.activate('/products/') # Activate by URL True >>> menu.activate('Home') # Activate by text True
- add_item(item: MenuItem) → None[source]#
Add a single
MenuItemto ourselves.- Parameters:
item – the menu item to add to ourselves.
- build_menu(items: Iterable[MenuItem]) → None[source]#
Recurse through
itemsand build out our menu and any submenus.For each
iteminitems, ifitem.itemsis not empty, add a submenu, otherwise add simple item.- Parameters:
items – the list of menu items to add to the list
- get_content(**kwargs) → str[source]#
Actually build out the menu from our list of
MenuItems. We do this inget_contentinstead of in__init__so that we catch any menu items added viaadd_itemafter instantiation.
- class MenuHeading(text: str | None = None, **kwargs)[source]#
Bases:
BlockA heading element for grouping menu items.
This widget creates a styled heading within a Menu to separate groups of items. It’s typically used for section titles in navigation menus.
Examples
from wildewidgets import MenuHeading heading = MenuHeading(text='Settings')
Notes
This is often created automatically from MenuItem objects that have no URL and no children.
- Parameters:
text – The heading text to display
- Keyword Arguments:
**kwargs – Additional keyword arguments passed to parent Block class
- block: str = 'nav-link nav-subtitle'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- class MenuItem(text: str, icon: str | wildewidgets.widgets.base.Block | None = None, url: str | None = None, items: list[wildewidgets.widgets.navigation.MenuItem] = <factory>, active: bool = False)[source]#
Bases:
objectA menu item definition for use in
Menuand related components.This dataclass simplifies the creation of complex menu structures by allowing nested hierarchies of menu items. It’s used by various menu components to create navigation structures without having to manually build the DOM elements.
The only required attribute/keyword argument is text. If url is not provided, the item will be rendered as a section title in menus. If items is not empty, the item will be rendered as a dropdown or submenu.
- icon#
Optional icon to display next to the text (either a string name of a Bootstrap icon or a TablerMenuIcon instance)
- Type:
str | wildewidgets.widgets.base.Block | None
- items#
Optional list of nested MenuItem objects for dropdown menus
Examples
Basic menu item:
from wildewidgets import MenuItem item = MenuItem(text="Home", url="/", icon="house")
Section header (no URL):
header = MenuItem(text="Management")
Dropdown menu:
from wildewidgets import MenuItem dropdown = MenuItem( text="Settings", icon="gear", items=[ MenuItem(text="Profile", url="/profile"), MenuItem(text="Preferences", url="/prefs") ] )
- set_active(text: str) → bool[source]#
Mark this item as active if it matches the given text or URL.
This method recursively checks this item and its children for a match:
If text appears to be a URL, it’s compared against the item’s url
If text is not a URL, it’s compared against the item’s text
If no match is found, the method is called recursively on all child items
- Parameters:
text – The text or URL to match against
- Returns:
True if this item or any of its children was set to active
- Return type:
Examples
from wildewidgets import MenuItem menu_item = MenuItem(text="Products", url="/products/") menu_item.set_active("/products/") # Match by URL menu_item.set_active("Products") # Match by text
- icon: str | wildewidgets.widgets.base.Block | None = None#
this is either the name of a bootstrap icon, or a
Block
- property is_active: bool#
Check if this menu item or any of its children is marked as active.
This property recursively checks the active state of this item and all its children. It returns True if either this item is active or any child item is active.
- Returns:
True if this item or any of its child items is active
- Return type:
- items: list[wildewidgets.widgets.navigation.MenuItem]#
a submenu under this menu item
- class NavDropdownControl(text: str | None = None, icon: str | wildewidgets.widgets.icons.TablerMenuIcon | None = None, active: bool = False, button_id: str | None = None, **kwargs)[source]#
Bases:
LinkA control button for dropdown menus.
This widget creates a link that toggles the visibility of a dropdown menu. It can include an optional icon and handles the open/closed state.
- icon#
Optional icon to display
- Type:
Examples
… code-block:: python
from wildewidgets import NavDropdownControl
- control = NavDropdownControl(
text=’Options’, button_id=’options-dropdown’
)
- control = NavDropdownControl(
text=’Options’, icon=’gear’, button_id=’options-dropdown’
)
- Parameters:
text – The text to display
icon – Optional icon to display
active – Whether this item should be highlighted as active
button_id – CSS ID for this button (required)
**kwargs – Additional keyword arguments passed to parent Link class
- Raises:
NavDropdownControl.RequiredAttrOrKwarg – If text is not provided
NavDropdownControl.RequiredAttrOrKwarg – If button_id is not provided
- collapse() → None[source]#
Set the dropdown to collapsed state.
This updates the aria-expanded attribute to ‘false’ to indicate that the associated dropdown menu is closed.
- expand() → None[source]#
Set the dropdown to expanded state.
This updates the aria-expanded attribute to ‘true’ to indicate that the associated dropdown menu is open.
- active: bool#
This item is active, but nothing in the related
DropdownMenuis
- aria_attributes: dict[str, str] = {'expanded': 'false'}#
Additional
aria-attributes to set on this block
- block: str = 'nav-link'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- button_id: str | None = None#
The CSS Id to assign to this button. We need this to tie the button to the actual
DropdownItem
- data_attributes: dict[str, str] = {'auto-close': 'true', 'toggle': 'dropdown'}#
Additional
data-bs-attributes to set on this block
- icon: str | TablerMenuIcon | None = None#
Either the name of a Bootstrap icon, or a
TablerMenuIconclass or subclass
- class NavDropdownItem(*items: MenuItem, text: str | None = None, icon: str | wildewidgets.widgets.icons.TablerMenuIcon | None = None, url: str | None = None, active: bool = False, **kwargs)[source]#
Bases:
BlockAn item in a
Menuthat opens a dropdown submenu.Typically, you won’t use this directly, but instead it will be created for you from a
MenuItemspecification whenMenuItem.itemsis not empty.Example
… code-block:: python
from wildewidgets import Menu, MenuItem, NavDropdownItem
- sub_items = [
MenuItem(text=’One’, url=’/one’, icon=’1-circle’), MenuItem(text=’Two’, url=’/two’, icon=’2-circle’), MenuItem(text=’Three’, url=’/three’, icon=’3-circle’),
] item = NavDropdownItem(*sub_items, text=’My Submenu’, icon=’target’) menu = Menu(item)
- Parameters:
*items – the list of
MenuItemobjects to insert into this menu- Keyword Arguments:
text – the text for the menu item
icon – this is either the name of a Bootstrap icon, or a
TablerMenuIconclass or subclass
- Raises:
ValueError – one or more of the settings failed validation
- get_context_data(**kwargs) → dict[str, Any][source]#
Overrides
wildewidgets.widgets.base.Block.get_context_data.Show our menu if either
activeisTrueor any item in ourmenuis active. We do this here instead of in our constructor so that any menu item activation that happens after instance construction time is accounted for.
- active#
The control for opening the dropdown menu is active, but nothing in the related
DropdownMenuis active
- block: str = 'nav-item dropdown'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- control: NavDropdownControl | ClickableNavDropdownControl#
The control that opens and closes
menu
- icon: str | TablerMenuIcon | None = None#
this is either the name of a bootstrap icon, or a
TablerMenuIconclass or subclass
- menu: DropdownMenu#
The
DropdownMenuthatcontrolopens
- class NavItem(text: str | None = None, icon: str | wildewidgets.widgets.icons.TablerMenuIcon | None = None, url: str | None = None, active: bool = False, item: wildewidgets.widgets.navigation.MenuItem | None = None, **kwargs)[source]#
Bases:
BlockA navigation item for use in menus.
This widget creates a list item with a link or heading, optionally with an icon. It represents a single navigation element in a menu or navbar.
- icon#
Optional icon to display (string name or TablerMenuIcon)
- Type:
Examples
With keyword arguments:
from wildewidgets import NavItem, TablerMenuIcon icon = TablerMenuIcon(icon='home') item = NavItem(text='Home', url='/', icon=icon)
With a
MenuItem:from wildewidgets import NavItem, MenuItem menu_item = MenuItem(text='Home', url='/', icon='home') item = NavItem(item=menu_item)
As a section heading:
from wildewidgets import NavItem heading = NavItem(text='Settings')
- Keyword Arguments:
text – The text to display
icon – Optional icon to display (string name or TablerMenuIcon)
url – Optional URL to link to
active – Whether this item should be highlighted as active
item – A MenuItem object to create this NavItem from
**kwargs – Additional keyword arguments passed to parent Block class
- Raises:
ValueError – If both item and other parameters are provided
ValueError – If no text is provided
- block: str = 'nav-item'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- icon: str | TablerMenuIcon | None = None#
Either the name of a Bootstrap icon, or a
TablerMenuIconobject
- class NavLinkToggle(text: str | None = None, icon: str | wildewidgets.widgets.icons.TablerMenuIcon | None = None, active: bool = False, collapse_id: str | None = None, **kwargs)[source]#
Bases:
LinkA toggle control for collapsible content.
This widget creates a link that toggles the visibility of a collapsible element. It includes styling for showing open/closed state and can optionally include an icon.
- icon#
Optional icon to display
- Type:
Example
from wildewidgets import NavLinkToggle toggle = NavLinkToggle( text='Advanced Options', collapse_id='advanced-options' )
- Keyword Arguments:
text – The text to display
icon – Optional icon to display
active – Whether this item should be highlighted as active
collapse_id – CSS ID of the element to toggle
**kwargs – Additional keyword arguments passed to parent Link class
- Raises:
NavLinkToggle.RequiredAttrOrKwarg – If collapse_id is not provided
NavLinkToggle.RequiredAttrOrKwarg – If text is not provided
- collapse() → None[source]#
Set the toggle to collapsed state.
This updates the aria-expanded attribute to ‘false’ to indicate that the associated collapsible element is closed.
- expand() → None[source]#
Set the toggle to expanded state.
This updates the aria-expanded attribute to ‘true’ to indicate that the associated collapsible element is open.
- active: bool#
This item is active, but nothing in the related
DropdownMenuis
- aria_attributes: dict[str, str] = {'expanded': 'false'}#
Additional
aria-attributes to set on this block
- block: str = 'nav-link'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- data_attributes: dict[str, str] = {'toggle': 'collapse'}#
Additional
data-bs-attributes to set on this block
- icon: str | TablerMenuIcon | None = None#
Either the name of a Bootstrap icon, or a
TablerMenuIconclass or subclass
- class Navbar(*blocks: Block, contents_id: str | None = None, branding: wildewidgets.widgets.base.Block | None = None, hide_below_viewport: str | None = None, container_size: str | None = None, dark: bool | None = None, background_color: str | None = None, **kwargs)[source]#
Bases:
BlockA Bootstrap navbar component for site navigation.
This class creates a horizontal Bootstrap navbar that can contain branding, menus, and other navigation elements. It handles responsive behavior and can be customized with different colors and breakpoints.
- branding#
Block to display as the navbar brand/logo
- Type:
- contents#
List of blocks to include in the navbar
- inner#
Container block for navbar contents
- menu_container#
Container for menu items that collapse on small screens
Examples
With a subclass:
- … code-block:: python
from wildewidgets import Navbar, Menu, MenuItem, LinkedImage
- class MyMenu(Menu):
items = [MenuItem(text=’One’, url=’/one’, icon=’target’)]
- class MyNavbar(Navbar):
- branding = LinkedImage(
src=’/static/branding.png’, alt=’My Brand’, url=’#’
) contents = [MyMenu()]
With constructor arguments:
… code-block:: python
from wildewidgets import Navbar, Menu, MenuItem, LinkedImage
- branding = LinkedImage(
src=’/static/branding.png’, alt=’My Brand’, url=’#’
) items = [MenuItem(text=’One’, url=’/one’), … ] menu = Menu(*items) sidebar = Navbar(menu, branding=branding)
Adding menus later:
… code-block:: python
from wildewidgets import Navbar, Menu, MenuItem
items2 = [MenuItem(text=’Foo’, url=’/foo’), … ] menu2 = Menu(*items2) sidebar.add_to_menu_section(menu2)
- Parameters:
*blocks – Blocks to add to the navbar
contents_id – CSS ID for the menu container
branding – Block to display as the navbar brand/logo
hide_below_viewport – Viewport size at which the menu collapses
container_size – Width of the navbar container
dark – Whether to use dark styling
background_color – Background color name
**kwargs – Additional keyword arguments passed to parent Block class
- Raises:
ValueError – If hide_below_viewport is not a valid breakpoint
ValueError – If background_color is not a valid color
- activate(text: str) → bool[source]#
Activate the menu item that matches the given text or URL.
This method searches through all Menu blocks in the navbar and activates the first menu item that matches the provided text or URL.
- Parameters:
text – The text or URL to match against menu items
- Returns:
True if a matching menu item was found and activated
- Return type:
Example
… code-block:: python
from wildewidgets import Navbar, Menu, MenuItem
navbar = Navbar() menu = Menu(MenuItem(text=’Home’, url=’/’)) navbar.add_to_menu_section(menu) navbar.activate(‘Home’)
- add_blocks() → None[source]#
Override the parent method to do nothing.
This method is intentionally empty to prevent blocks from being added directly to the navbar. Instead, blocks should be added to the menu section using add_to_menu_section().
- add_to_menu_section(block: Block) → None[source]#
Add a block to the collapsible menu section of the navbar.
This method should be used instead of add_block() to add navigation elements to the navbar. Items added this way will be part of the collapsible menu that toggles with the hamburger button on small screens.
- Parameters:
block – The block to add to the menu section
Example
… code-block:: python
from wildewidgets import Navbar, Menu, MenuItem
navbar = Navbar() menu = Menu(MenuItem(text=’Home’, url=’/’)) navbar.add_to_menu_section(menu)
- build_brand() → None[source]#
Build the navbar brand element.
This method adds the brand/logo element to the navbar’s inner container. It can be overridden in subclasses to customize branding behavior.
- VALID_BACKGROUND_COLORS: Final[list[str]] = ['blue', 'azure', 'indigo', 'purple', 'pink', 'red', 'orange', 'yellow', 'lime', 'green', 'teal', 'cyan', 'white']#
Valid background colors. Note that these are Tabler colors, not Bootstrap colors. We use Tabler colors because Tabler also defines an appropriate foreground color for each background color.
- VALID_BREAKPOINTS: Final[list[str]] = ['sm', 'md', 'lg', 'xl', 'xxl']#
Valid values for
navbar-expand-. From Navbar: How It Works
- background_color: str | None = None#
#1d273b- Type:
If
darkisTrue, set the background color. Default
- contents_id: str = 'sidebar-menu'#
the CSS id of the menu container. Typically you won’t need to change this unless you have namespace collisions with other CSS ids on your page.
- class NavbarMixin[source]#
Bases:
objectA mixin for Django class-based views to manage navigation components.
This mixin provides a standardized way to integrate navigation components (like navbars and submenus) into Django views. It adds navbar instances to the template context and handles the activation of menu items based on the current page.
To use this mixin: 1. Define your Navbar classes 2. Subclass this mixin in your views 3. Set the navbar_class and menu_item attributes 4. In your template, render the “menu” and “submenu” context variables
- navbar_class#
The Navbar subclass to use as primary navigation
- secondary_navbar_class#
Optional Navbar subclass for secondary navigation
- Type:
- secondary_menu_item#
Text or URL of the item to mark as active in the secondary navbar
- Type:
str | None
Examples
Creating a view with navigation:
class MainNavbar(Navbar): # Navbar definition... class ProjectsView(NavbarMixin, ListView): navbar_class = MainNavbar menu_item = 'Projects' # Will highlight "Projects" in the menu def get_queryset(self): # View implementation...
In your template:
{% wildewidgets menu %} <div class="container"> <!-- Your page content --> </div>- get_context_data(**kwargs) → dict[str, Any][source]#
Add navigation components to the template context.
This method: 1. Creates the primary navbar and adds it as ‘menu’ 2. Activates the appropriate menu item 3. If applicable, creates the secondary navbar and adds it as ‘submenu’ 4. Activates the appropriate secondary menu item
- Returns:
The updated context dictionary
- Return type:
Dict[str, Any]
- get_menu_item() → str | None[source]#
Return the text or URL of an item to set active among the menus in our main
Navbarclass.- Returns:
The class of the
Navbarsubclass to use for our main menu.
- get_navbar() → wildewidgets.widgets.navigation.Navbar | None[source]#
Create and return an instance of the primary navbar.
This method instantiates the navbar_class and returns it. Override this method if you need custom initialization of your navbar.
- Returns:
An instance of the primary navbar class
- Return type:
- Raises:
ImproperlyConfigured – If navbar_class is None
- get_navbar_class() → type[wildewidgets.widgets.navigation.Navbar][source]#
Return the
Navbarsubclass for the main menu. Overriding this will allow you to programmatically determine your at view time.- Returns:
The class of the
Navbarsubclass to use for our main menu.
- get_secondary_menu_item() → str | None[source]#
Return the text of an item to set active in our secondary menu
- get_secondary_navbar() → wildewidgets.widgets.navigation.Navbar | None[source]#
Instantiate and return our
Navbarsubclass for our secondary navbar.- Returns:
The instantiated
Navbarsubclass instance to use for our secondary menu, if any.
- get_secondary_navbar_class() → type[wildewidgets.widgets.navigation.Navbar] | None[source]#
Return our
Navbarsubclass for the secondary navbar.- Returns:
The class of the
Navbarsubclass to use for our secondary navbar, if any.
- menu_item: str | None = None#
The text or URL of an item in one of our
navbar_classmenus to set active
- secondary_menu_item: str | None = None#
The text or URL of an item in one of our
secondary_navbar_classmenus to set active
- secondary_navbar_class: type[wildewidgets.widgets.navigation.Navbar] | None = None#
The
Navbarsubclass that holds our secondary menus
- class NavigationTogglerButton(target: str | None = None, label: str | None = None, **kwargs)[source]#
Bases:
BlockA button that toggles responsive navigation components.
This widget creates the familiar “hamburger” button that appears on mobile viewports to toggle the visibility of navigation menus. It’s designed to work with Bootstrap’s responsive navbar collapse behavior.
Examples
… code-block:: python
from wildewidgets import NavigationTogglerButton
toggler = NavigationTogglerButton(target=’main-nav’)
This produces HTML similar to:
<button type="button" class="navbar-toggler collapsed" data-toggle="collapse" data-target="#main-nav" aria-expanded="false" aria-controls="main-nav" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button>
- aria_attributes: dict[str, str] = {'expanded': 'false'}#
Additional
aria-attributes to set on this block
- block: str = 'navbar-toggler'#
block is the official wildewidgets name of the block; it can’t be changed by constructor kwargs
- class TablerVerticalNavbar(*args, wide: bool | None = None, **kwargs)[source]#
Bases:
NavbarA vertical navbar styled with Tabler design elements.
This navbar variant is designed to be displayed as a sidebar with a vertical orientation. It has dark styling by default and provides consistent width options.
Features: * Vertical orientation instead of horizontal * Dark mode by default * Fixed width (15rem or 18rem if wide=True) * Fixed position for scrolling pages * Includes open/close animations
Examples
… code-block:: python
from wildewidgets import TablerVerticalNavbar, Menu, MenuItem, LinkedImage
- branding = LinkedImage(
src=’/static/branding.png’, alt=’My Brand’, url=’https://example.com’, width=’100%’
) items = [MenuItem(text=’Home’, url=’/home’)] menu = Menu(*items) sidebar = TablerVerticalNavbar(menu, branding=branding)
- Parameters:
*args – Positional arguments passed to parent Navbar class
- Keyword Arguments:
wide – If True, use wider 18rem layout instead of 15rem
**kwargs – Additional keyword arguments passed to parent Navbar class
- is_url(text: str) → bool[source]#
Check if a string appears to be a URL or path.
This function uses regular expressions to determine if the provided text matches patterns for either a relative path (starting with slash) or an absolute URL (with protocol).
- Parameters:
text – The string to check
- Returns:
True if the text looks like a URL or path, False otherwise
- Return type:
Examples
>>> is_url("/some/path") True >>> is_url("https://example.com") True >>> is_url("not a url") False
- path_validator_re = re.compile('^/\\S+$', re.IGNORECASE)#
A regular expression that matches a valid URL path. A valid URL path starts with a slash and does not contain whitespace.
- url_validator_re = re.compile('^(?:http)s?://(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|localhost|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(?::\\d+)?(?:/?|[/?]\\S+)$', re.IGNORECASE)#
A regular expression that matches a valid URL. A valid URL starts with http:// or https://, followed by a domain or IP address, and may include a port number and path.
A valid URL may also be a localhost URL.
The domain must be a valid top-level domain or a valid IP address.
The port number, if present, must be a valid integer.
The path, if present, must not contain whitespace.
The URL may end with a slash or a query string.
- Note: This regex is not perfect and may not match all valid URLs, but it should
match most common cases. It is designed to be simple and easy to read. If you need a more complex URL validation, consider using a library like validators or
django.core.validators.URLValidator.