Bootstrap-based Sphinx theme from the PyData community
—
Helper functions for theme configuration management, template processing, sidebar customization, and Sphinx integration utilities.
Functions for accessing and validating theme configuration options.
def get_theme_options_dict(app: Sphinx) -> Dict[str, Any]:
"""
Return theme options for the application with a fallback if they don't exist.
Checks both app.builder.theme_options (the preferred location created by Sphinx
as a copy of app.config.html_theme_options) and app.config.html_theme_options
(the user configuration from conf.py) with appropriate fallbacks.
Parameters:
- app (Sphinx): Sphinx application instance
Returns:
Dict[str, Any]: Theme options dictionary or empty dict if none exist
"""
def config_provided_by_user(app: Sphinx, key: str) -> bool:
"""
Check if the user has manually provided the config.
Determines whether a configuration key was explicitly set by the user
in their conf.py file rather than using default values.
Parameters:
- app (Sphinx): Sphinx application instance
- key (str): Configuration key to check
Returns:
bool: True if user provided the config, False if using defaults
"""Helper functions for processing document nodes and handling docutils compatibility.
def traverse_or_findall(
node: Node, condition: Union[Callable, type], **kwargs
) -> Iterable[Node]:
"""
Triage node.traverse (docutils <0.18.1) vs node.findall.
Provides compatibility between different docutils versions by using
the appropriate method for traversing document nodes.
Parameters:
- node (Node): Document node to traverse
- condition (Union[Callable, type]): Condition or type to match
- **kwargs: Additional arguments passed to traverse/findall
Returns:
Iterable[Node]: Iterator of matching nodes
"""
def escape_ansi(string: str) -> str:
"""
Helper function to remove ansi coloring from sphinx warnings.
Strips ANSI escape sequences from strings, useful for cleaning
up log messages and warnings.
Parameters:
- string (str): String potentially containing ANSI codes
Returns:
str: String with ANSI codes removed
"""Warning and logging management for theme messages.
def maybe_warn(app: Sphinx, msg, *args, **kwargs):
"""
Wraps the Sphinx logger to allow warning suppression.
Provides configurable warning behavior based on theme options.
When surface_warnings is True, messages are logged as warnings.
Otherwise, they are logged as info messages.
Parameters:
- app (Sphinx): Sphinx application instance
- msg: Warning message to log
- *args: Additional arguments for logging
- **kwargs: Additional keyword arguments for logging
"""Functions for managing secondary sidebar content and template processing.
def set_secondary_sidebar_items(
app: Sphinx, pagename: str, templatename: str, context, doctree
) -> None:
"""
Set the secondary sidebar items to render for the given pagename.
Processes theme_secondary_sidebar_items configuration to determine
which sidebar templates should be displayed on each page, supporting
both global and page-specific sidebar configurations.
Parameters:
- app (Sphinx): Sphinx application instance
- pagename (str): Name of current page
- templatename (str): Template being used
- context: Page context dictionary
- doctree: Document tree for the page
"""
def _update_and_remove_templates(
app: Sphinx,
context: Dict[str, Any],
templates: Union[List, str],
section: str,
templates_skip_empty_check: Optional[List[str]] = None,
) -> List[str]:
"""
Update templates to include html suffix if needed; remove templates which render empty.
Processes template lists to:
- Add .html suffix to templates without extensions
- Remove templates that render to empty strings (performance optimization)
- Skip empty checks for specified templates that are slow to render
Parameters:
- app (Sphinx): Sphinx application instance
- context (Dict[str, Any]): Page context for template rendering
- templates (Union[List, str]): Template names or comma-separated string
- section (str): Template section name (e.g., 'theme_navbar_start')
- templates_skip_empty_check (Optional[List[str]]): Templates to skip empty check
Returns:
List[str]: Filtered list of template names with .html suffixes
"""
def _get_matching_sidebar_items(
pagename: str, sidebars: Dict[str, List[str]]
) -> List[str]:
"""
Get the matching sidebar templates to render for the given pagename.
Matches page names against sidebar configuration patterns, supporting
glob patterns and wildcard matching. Emits warnings for ambiguous matches.
Parameters:
- pagename (str): Name of the current page
- sidebars (Dict[str, List[str]]): Mapping of patterns to sidebar templates
Returns:
List[str]: List of sidebar template names for the page
"""
def _has_wildcard(pattern: str) -> bool:
"""
Check whether the pattern contains a wildcard.
Detects glob-style wildcards in patterns used for sidebar matching.
Parameters:
- pattern (str): Pattern string to check
Returns:
bool: True if pattern contains wildcards (*, ?, [])
"""# Check if user provided custom configuration
if config_provided_by_user(app, 'html_permalinks_icon'):
# User set custom permalink icon
pass
else:
# Use theme default
app.config.html_permalinks_icon = "#"
# Get theme options with fallback
theme_options = get_theme_options_dict(app)
logo_config = theme_options.get("logo", {})# conf.py - Global sidebar configuration
html_theme_options = {
"secondary_sidebar_items": ["page-toc", "edit-this-page"]
}
# Page-specific sidebar configuration
html_theme_options = {
"secondary_sidebar_items": {
# Specific pages
"index": ["search-field"],
"contact": ["search-field", "edit-this-page"],
# Pattern matching
"user-guide/**": ["page-toc", "edit-this-page"],
"api/**": ["page-toc", "sourcelink"],
"tutorials/*": ["page-toc", "edit-this-page", "download-page"],
# Wildcards
"**/examples": ["page-toc", "download-page"],
"reference/*/methods": ["page-toc", "edit-this-page"]
}
}# Templates can be specified as lists or comma-separated strings
navbar_templates = ["navbar-logo", "navbar-nav", "search-field"]
# or
navbar_templates = "navbar-logo, navbar-nav, search-field"
# Templates are automatically processed to:
# 1. Add .html extension if missing
# 2. Remove templates that render empty (unless skipped)
# 3. Handle slow-rendering templates efficiently# conf.py - Control warning visibility
html_theme_options = {
"surface_warnings": True, # Show warnings prominently
# or
"surface_warnings": False, # Log warnings as info messages
}# Docutils compatibility for node traversal
from pydata_sphinx_theme.utils import traverse_or_findall
from docutils import nodes
# Works with both old and new docutils versions
for ref_node in traverse_or_findall(document, nodes.reference):
# Process reference nodes
passValid section names for _update_and_remove_templates:
theme_navbar_start, theme_navbar_center, theme_navbar_persistent, theme_navbar_endtheme_article_header_start, theme_article_header_endtheme_article_footer_items, theme_content_footer_itemstheme_footer_start, theme_footer_center, theme_footer_endtheme_primary_sidebar_end, theme_secondary_sidebar_itemssidebarsSPHINX_LOGGER = logging.getLogger(__name__)The module-level logger instance used for theme-related log messages.
Install with Tessl CLI
npx tessl i tessl/pypi-pydata-sphinx-theme