0
# PyData Sphinx Theme
1
2
A comprehensive Bootstrap-based Sphinx documentation theme specifically designed for the PyData community ecosystem. The theme provides a clean, three-column layout with extensive customization options including light/dark theme switching, analytics integration, flexible navigation components, and comprehensive branding features. It's built with modern web technologies while maintaining compatibility with Sphinx documentation workflows and is designed for maximum reusability across scientific Python documentation projects.
3
4
## Package Information
5
6
- **Package Name**: pydata-sphinx-theme
7
- **Language**: Python
8
- **Installation**: `pip install pydata-sphinx-theme`
9
- **Dependencies**: sphinx>=6.1, beautifulsoup4, docutils, Babel, pygments>=2.7, accessible-pygments, typing-extensions
10
11
## Core Imports
12
13
```python
14
import pydata_sphinx_theme
15
from pydata_sphinx_theme import __version__
16
```
17
18
The theme is typically configured through Sphinx's configuration system rather than direct imports:
19
20
```python
21
# In conf.py
22
html_theme = "pydata_sphinx_theme"
23
```
24
25
For programmatic access to theme information:
26
27
```python
28
import pydata_sphinx_theme
29
print(f"Theme version: {pydata_sphinx_theme.__version__}")
30
```
31
32
## Basic Usage
33
34
```python
35
# conf.py - Basic Sphinx configuration
36
html_theme = "pydata_sphinx_theme"
37
38
# Optional: Theme customization
39
html_theme_options = {
40
"logo": {
41
"image_light": "logo-light.png",
42
"image_dark": "logo-dark.png",
43
"text": "My Project"
44
},
45
"icon_links": [
46
{
47
"name": "GitHub",
48
"url": "https://github.com/user/repo",
49
"icon": "fa-brands fa-square-github",
50
"type": "fontawesome",
51
}
52
],
53
"use_edit_page_button": True,
54
"show_toc_level": 2,
55
"navbar_align": "left",
56
}
57
58
# Context variables for edit buttons and version switching
59
html_context = {
60
"github_user": "user",
61
"github_repo": "repo",
62
"github_version": "main",
63
"doc_path": "docs/",
64
}
65
```
66
67
## Architecture
68
69
The theme follows Sphinx's extension architecture pattern:
70
71
- **Theme Registration**: Registers itself as a Sphinx HTML theme via entry points
72
- **Event System**: Connects to Sphinx build events for configuration and template processing
73
- **Template Processing**: Processes Jinja2 templates with Bootstrap 5 styling
74
- **Asset Management**: Handles CSS/JS compilation via webpack and manages static assets
75
- **Internationalization**: Supports multiple languages through Babel message catalogs
76
77
## Capabilities
78
79
### Theme Setup and Configuration
80
81
Core functionality for registering the theme with Sphinx and managing configuration options, including theme options validation, deprecated key handling, and analytics integration.
82
83
```python { .api }
84
def setup(app: Sphinx) -> Dict[str, str]:
85
"""Setup the Sphinx application."""
86
87
def update_config(app):
88
"""Update config with new default values and handle deprecated keys."""
89
```
90
91
[Theme Setup](./theme-setup.md)
92
93
### Template and Context Management
94
95
Template processing functionality that manages Jinja2 template rendering, asset injection, and HTML context preparation for each page during the build process.
96
97
```python { .api }
98
def update_and_remove_templates(
99
app: Sphinx, pagename: str, templatename: str, context, doctree
100
) -> None:
101
"""Update template names and assets for page build."""
102
103
def _fix_canonical_url(
104
app: Sphinx, pagename: str, templatename: str, context: dict, doctree
105
) -> None:
106
"""Fix the canonical URL when using the dirhtml builder."""
107
```
108
109
[Template Management](./template-management.md)
110
111
### Utilities and Configuration Helpers
112
113
Helper functions for theme configuration management, template processing, sidebar customization, and Sphinx integration utilities.
114
115
```python { .api }
116
def get_theme_options_dict(app: Sphinx) -> Dict[str, Any]:
117
"""Return theme options for the application w/ a fallback if they don't exist."""
118
119
def config_provided_by_user(app: Sphinx, key: str) -> bool:
120
"""Check if the user has manually provided the config."""
121
122
def set_secondary_sidebar_items(
123
app: Sphinx, pagename: str, templatename: str, context, doctree
124
) -> None:
125
"""Set the secondary sidebar items to render for the given pagename."""
126
```
127
128
[Utilities](./utilities.md)
129
130
### Edit Page Integration
131
132
Functionality for generating "edit this page" links that work with GitHub, GitLab, and Bitbucket repositories, supporting custom URL templates and multiple version control platforms.
133
134
```python { .api }
135
def setup_edit_url(
136
app: Sphinx, pagename: str, templatename: str, context, doctree
137
) -> None:
138
"""Add a function that jinja can access for returning the edit URL of a page."""
139
```
140
141
[Edit Page Integration](./edit-page.md)
142
143
### Logo and Branding Management
144
145
Logo handling system that supports light/dark theme variants, custom logo positioning, and automatic asset copying to the build output directory.
146
147
```python { .api }
148
def setup_logo_path(
149
app: Sphinx, pagename: str, templatename: str, context: dict, doctree: Node
150
) -> None:
151
"""Set up relative paths to logos in HTML templates."""
152
153
def copy_logo_images(app: Sphinx, exception=None) -> None:
154
"""Copy logo image to the _static directory."""
155
```
156
157
[Logo Management](./logo-management.md)
158
159
### Syntax Highlighting
160
161
Pygments integration that provides dynamic light/dark theme switching for code syntax highlighting, with automatic fallbacks and custom style generation.
162
163
```python { .api }
164
def get_pygments_stylesheet(light_style: str, dark_style: str) -> str:
165
"""Generate the theme-specific pygments.css."""
166
167
def overwrite_pygments_css(app: Sphinx, exception=None):
168
"""Overwrite pygments.css to allow dynamic light/dark switching."""
169
```
170
171
[Syntax Highlighting](./syntax-highlighting.md)
172
173
### Link Processing
174
175
Transform system for automatically shortening and styling GitHub and GitLab repository links in documentation, making them more readable and visually consistent.
176
177
```python { .api }
178
class ShortenLinkTransform(SphinxPostTransform):
179
"""Transform to shorten GitHub/GitLab links."""
180
181
def run(self, **kwargs):
182
"""Run the Transform object."""
183
184
def parse_url(self, uri: ParseResult) -> str:
185
"""Parse the content of the url with respect to the selected platform."""
186
```
187
188
[Link Processing](./link-processing.md)
189
190
### Table of Contents Processing
191
192
Advanced TOC processing with support for inline math rendering, ancestor page determination, and custom toctree function injection for enhanced navigation.
193
194
```python { .api }
195
def add_inline_math(node: Node) -> str:
196
"""Render a node with HTML tags that activate MathJax processing."""
197
198
def add_toctree_functions(
199
app: Sphinx, pagename: str, templatename: str, context, doctree
200
) -> None:
201
"""Add toctree-related functions to template context."""
202
```
203
204
[TOC Processing](./toc-processing.md)
205
206
### HTML Translation
207
208
Bootstrap-specific HTML translator that modifies Sphinx's default HTML output to be compatible with Bootstrap 5 styling, including table formatting and accessibility improvements.
209
210
```python { .api }
211
class BootstrapHTML5TranslatorMixin:
212
"""Mixin HTML Translator for a Bootstrap-ified Sphinx layout."""
213
214
def starttag(self, *args, **kwargs):
215
"""Perform small modifications to tags."""
216
217
def visit_table(self, node):
218
"""Custom visit table method."""
219
220
def depart_table(self, node):
221
"""Custom depart_table method to close the scrollable div."""
222
223
def setup_translators(app: Sphinx):
224
"""Add bootstrap HTML functionality if we are using an HTML translator."""
225
```
226
227
[HTML Translation](./html-translation.md)
228
229
## Types
230
231
```python { .api }
232
# Version constant
233
__version__: str # Current theme version (e.g., "0.16.1")
234
235
# From typing imports
236
from typing import Dict, Any, List, Optional, Union, Callable, Iterable, ClassVar
237
from pathlib import Path
238
from urllib.parse import ParseResult
239
240
# Sphinx types
241
from sphinx.application import Sphinx
242
from sphinx.builders.dirhtml import DirectoryHTMLBuilder
243
from docutils.nodes import Node
244
245
# Theme-specific types
246
ThemeOptions = Dict[str, Any]
247
TemplateList = Union[List[str], str]
248
IconLinkConfig = Dict[str, str] # Contains url, icon, name, type keys
249
LogoConfig = Dict[str, str] # Contains image_light, image_dark, text, link keys
250
251
# Additional types from the codebase
252
AnalyticsConfig = Dict[str, Union[str, Dict[str, str]]] # Contains google_analytics_id, plausible_analytics_domain, etc.
253
SwitcherConfig = Dict[str, Union[str, bool]] # Contains json_url, version_match, check_switcher
254
LinkInfo = Dict[str, Union[str, bool]] # Contains is_current, href, title, is_external
255
```