Bootstrap-based Sphinx theme from the PyData community
—
Advanced TOC processing with support for inline math rendering, ancestor page determination, and custom toctree function injection for enhanced navigation.
Renders mathematical expressions in section titles for proper display in navigation.
def add_inline_math(node: Node) -> str:
"""
Render a node with HTML tags that activate MathJax processing.
Converts mathematical expressions in section titles to HTML format
that MathJax can process. This is necessary because pydata-sphinx-theme's
headers ignore regular math outputs.
Parameters:
- node (Node): Document node containing mathematical expression
Returns:
str: HTML string with MathJax-compatible math markup
"""Determines ancestor pages for navigation breadcrumbs and hierarchy display.
def _get_ancestor_pagename(app: Sphinx, pagename: str, startdepth: int) -> str:
"""
Get the name of pagename's ancestor that is rooted startdepth levels below the global root.
Navigates the document hierarchy to find ancestor pages at specific depths,
supporting both Sphinx 7.2+ and earlier versions with appropriate compatibility.
Parameters:
- app (Sphinx): Sphinx application instance
- pagename (str): Name of the current page
- startdepth (int): Depth level to find ancestor at
Returns:
str: Name of the ancestor page at the specified depth
"""Adds toctree-related functionality to template context for enhanced navigation.
def add_toctree_functions(
app: Sphinx, pagename: str, templatename: str, context, doctree
) -> None:
"""
Add toctree-related functions to template context.
Injects custom navigation functions into the Jinja2 template context
to enable advanced table of contents features and navigation controls.
Parameters:
- app (Sphinx): Sphinx application instance
- pagename (str): Name of current page being processed
- templatename (str): Template being used
- context: Template context dictionary
- doctree: Document tree for the current page
"""The following functions are injected into template context and available in Jinja2 templates:
def suppress_sidebar_toctree(startdepth: int = 1, **kwargs) -> bool:
"""
Check if sidebar TocTree should be rendered for the current page.
Determines whether to display the sidebar TOC based on document structure
and configuration options.
Parameters:
- startdepth (int): Starting depth for TOC display (default: 1)
- **kwargs: Additional toctree options
Returns:
bool: True if sidebar TOC should be suppressed, False otherwise
"""
def unique_html_id(base_id: str) -> str:
"""
Create unique HTML IDs for elements to avoid conflicts.
Generates unique identifiers by tracking used IDs and appending
counters when duplicates are detected.
Parameters:
- base_id (str): Base identifier string
Returns:
str: Unique HTML ID string
"""
def generate_header_nav_html(
n_links_before_dropdown: int = 5,
dropdown_text: str = "More"
) -> str:
"""
Generate header navigation HTML with dropdown for overflow items.
Creates responsive navigation that collapses extra items into a dropdown
when the number of navigation links exceeds the specified limit.
Parameters:
- n_links_before_dropdown (int): Number of links before dropdown (default: 5)
- dropdown_text (str): Text for dropdown toggle (default: "More")
Returns:
str: HTML string for header navigation
"""
def generate_toctree_html(
kind: str,
startdepth: int = 1,
show_nav_level: int = 1,
**kwargs
) -> str:
"""
Generate sidebar toctree HTML.
Creates HTML for the sidebar table of contents with configurable
depth and display options.
Parameters:
- kind (str): Type of toctree to generate
- startdepth (int): Starting depth for toctree (default: 1)
- show_nav_level (int): Navigation level to show (default: 1)
- **kwargs: Additional toctree options
Returns:
str: HTML string for sidebar toctree
"""
def generate_toc_html(kind: str = "html") -> str:
"""
Generate within-page table of contents HTML.
Creates HTML for the page-level TOC showing section headings
and subsections within the current document.
Parameters:
- kind (str): Output format type (default: "html")
Returns:
str: HTML string for page TOC
"""
def navbar_align_class() -> str:
"""
Return navbar alignment CSS classes based on theme configuration.
Determines the appropriate Bootstrap classes for navbar alignment
based on the theme_navbar_align configuration option.
Returns:
str: CSS class string for navbar alignment
"""Additional utility functions for TOC processing:
def add_collapse_checkboxes(soup: BeautifulSoup) -> None:
"""
Add collapsible functionality to toctrees.
Modifies toctree HTML to include collapse/expand checkboxes
for hierarchical navigation sections.
Parameters:
- soup (BeautifulSoup): Parsed HTML soup object to modify
"""
def get_nonroot_toctree(
app: Sphinx,
pagename: str,
ancestorname: str,
toctree,
**kwargs
) -> str:
"""
Get partial TocTree fragments for non-root pages.
Generates toctree HTML for specific sections of the document
hierarchy, useful for creating contextual navigation.
Parameters:
- app (Sphinx): Sphinx application instance
- pagename (str): Current page name
- ancestorname (str): Name of ancestor page to start from
- toctree: Toctree object
- **kwargs: Additional toctree options
Returns:
str: HTML string for partial toctree
"""@dataclass
class LinkInfo:
"""
Information about navigation links in toctrees.
Attributes:
- is_current (bool): Whether this is the current page
- href (str): URL for the link
- title (str): Display title for the link
- is_external (bool): Whether link points to external site
"""
is_current: bool
href: str
title: str
is_external: boolSection Title with Math
=======================
Integration with :math:`\int_0^1 x^2 dx`
=========================================
Complex Equations
=================
The equation :math:`E = mc^2` demonstrates energy-mass equivalence.
Advanced Mathematics
====================
Quantum mechanics uses :math:`\hat{H}\psi = E\psi` as the fundamental equation.Mathematical Functions
======================
Fourier Transform: :math:`F(\omega) = \int_{-\infty}^{\infty} f(t) e^{-i\omega t} dt`
Matrix Operations
=================
Identity matrix: :math:`\mathbf{I} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}`The TOC processing enables breadcrumb navigation based on document hierarchy:
# Generated breadcrumb context
breadcrumbs = [
{"title": "Home", "url": "/"},
{"title": "User Guide", "url": "/user-guide/"},
{"title": "Advanced Topics", "url": "/user-guide/advanced/"},
{"title": "Current Page", "url": "#"}
].. toctree::
:maxdepth: 2
:caption: Contents:
introduction
user-guide/index
api/index
examples/indexResults in structured navigation with proper ancestor relationships.
# conf.py
html_theme_options = {
"show_toc_level": 2, # Depth of TOC display
"collapse_navigation": False, # Keep navigation expanded
"navigation_depth": 4, # Maximum navigation depth
}# conf.py
html_theme_options = {
# TOC display options
"show_toc_level": 3,
"show_nav_level": 2,
# Navigation behavior
"collapse_navigation": True,
"sticky_navigation": True,
"includehidden": True,
# Sidebar TOC
"secondary_sidebar_items": ["page-toc", "edit-this-page"],
}Mathematical Concepts
=====================
Linear Algebra: :math:`Ax = b`
-------------------------------
The fundamental equation of linear algebra.
Calculus: :math:`\frac{df}{dx}`
-------------------------------
Derivatives and their applications.
Statistics: :math:`\mu = \frac{1}{n}\sum_{i=1}^n x_i`
----------------------------------------------------
Mean calculation formula... toctree::
:maxdepth: 3
:caption: Documentation
:hidden:
getting-started/index
user-guide/index
api-reference/index
examples/index
Mathematical Analysis
=====================
.. toctree::
:maxdepth: 2
analysis/calculus
analysis/linear-algebra
analysis/statistics# conf.py - Custom TOC template
html_theme_options = {
"secondary_sidebar_items": ["custom-toc.html", "edit-this-page"]
}{# custom-toc.html #}
<nav class="bd-toc" id="bd-toc-nav">
<ul class="visible nav section-nav flex-column">
{% for toctree in toctrees %}
{{ toctree }}
{% endfor %}
</ul>
</nav>The TOC processing adds these variables to template context:
The math rendering integrates with Sphinx's MathJax configuration:
# conf.py
extensions = ['sphinx.ext.mathjax']
mathjax3_config = {
'tex': {
'inlineMath': [['$', '$'], ['\\(', '\\)']],
'displayMath': [['$$', '$$'], ['\\[', '\\]']],
}
}The TOC processing handles various edge cases:
The injected functions provide advanced navigation capabilities:
{# Template usage examples #}
{{ get_nav_object(maxdepth=2, collapse=true) }}
{{ generate_breadcrumbs(pagename) }}
{{ render_toc_tree(include_hidden=false) }}# conf.py - Conditional TOC based on page type
html_theme_options = {
"secondary_sidebar_items": {
"api/**": ["page-toc"], # API pages: only TOC
"examples/**": ["download-page"], # Examples: download links
"**": ["page-toc", "edit-this-page"] # Default: TOC + edit button
}
}Install with Tessl CLI
npx tessl i tessl/pypi-pydata-sphinx-theme