0
# Table of Contents Processing
1
2
Advanced TOC processing with support for inline math rendering, ancestor page determination, and custom toctree function injection for enhanced navigation.
3
4
## Capabilities
5
6
### Math Rendering Support
7
8
Renders mathematical expressions in section titles for proper display in navigation.
9
10
```python { .api }
11
def add_inline_math(node: Node) -> str:
12
"""
13
Render a node with HTML tags that activate MathJax processing.
14
15
Converts mathematical expressions in section titles to HTML format
16
that MathJax can process. This is necessary because pydata-sphinx-theme's
17
headers ignore regular math outputs.
18
19
Parameters:
20
- node (Node): Document node containing mathematical expression
21
22
Returns:
23
str: HTML string with MathJax-compatible math markup
24
"""
25
```
26
27
### Page Hierarchy Navigation
28
29
Determines ancestor pages for navigation breadcrumbs and hierarchy display.
30
31
```python { .api }
32
def _get_ancestor_pagename(app: Sphinx, pagename: str, startdepth: int) -> str:
33
"""
34
Get the name of pagename's ancestor that is rooted startdepth levels below the global root.
35
36
Navigates the document hierarchy to find ancestor pages at specific depths,
37
supporting both Sphinx 7.2+ and earlier versions with appropriate compatibility.
38
39
Parameters:
40
- app (Sphinx): Sphinx application instance
41
- pagename (str): Name of the current page
42
- startdepth (int): Depth level to find ancestor at
43
44
Returns:
45
str: Name of the ancestor page at the specified depth
46
"""
47
```
48
49
### TOC Function Injection
50
51
Adds toctree-related functionality to template context for enhanced navigation.
52
53
```python { .api }
54
def add_toctree_functions(
55
app: Sphinx, pagename: str, templatename: str, context, doctree
56
) -> None:
57
"""
58
Add toctree-related functions to template context.
59
60
Injects custom navigation functions into the Jinja2 template context
61
to enable advanced table of contents features and navigation controls.
62
63
Parameters:
64
- app (Sphinx): Sphinx application instance
65
- pagename (str): Name of current page being processed
66
- templatename (str): Template being used
67
- context: Template context dictionary
68
- doctree: Document tree for the current page
69
"""
70
```
71
72
### Template Context Functions
73
74
The following functions are injected into template context and available in Jinja2 templates:
75
76
```python { .api }
77
def suppress_sidebar_toctree(startdepth: int = 1, **kwargs) -> bool:
78
"""
79
Check if sidebar TocTree should be rendered for the current page.
80
81
Determines whether to display the sidebar TOC based on document structure
82
and configuration options.
83
84
Parameters:
85
- startdepth (int): Starting depth for TOC display (default: 1)
86
- **kwargs: Additional toctree options
87
88
Returns:
89
bool: True if sidebar TOC should be suppressed, False otherwise
90
"""
91
92
def unique_html_id(base_id: str) -> str:
93
"""
94
Create unique HTML IDs for elements to avoid conflicts.
95
96
Generates unique identifiers by tracking used IDs and appending
97
counters when duplicates are detected.
98
99
Parameters:
100
- base_id (str): Base identifier string
101
102
Returns:
103
str: Unique HTML ID string
104
"""
105
106
def generate_header_nav_html(
107
n_links_before_dropdown: int = 5,
108
dropdown_text: str = "More"
109
) -> str:
110
"""
111
Generate header navigation HTML with dropdown for overflow items.
112
113
Creates responsive navigation that collapses extra items into a dropdown
114
when the number of navigation links exceeds the specified limit.
115
116
Parameters:
117
- n_links_before_dropdown (int): Number of links before dropdown (default: 5)
118
- dropdown_text (str): Text for dropdown toggle (default: "More")
119
120
Returns:
121
str: HTML string for header navigation
122
"""
123
124
def generate_toctree_html(
125
kind: str,
126
startdepth: int = 1,
127
show_nav_level: int = 1,
128
**kwargs
129
) -> str:
130
"""
131
Generate sidebar toctree HTML.
132
133
Creates HTML for the sidebar table of contents with configurable
134
depth and display options.
135
136
Parameters:
137
- kind (str): Type of toctree to generate
138
- startdepth (int): Starting depth for toctree (default: 1)
139
- show_nav_level (int): Navigation level to show (default: 1)
140
- **kwargs: Additional toctree options
141
142
Returns:
143
str: HTML string for sidebar toctree
144
"""
145
146
def generate_toc_html(kind: str = "html") -> str:
147
"""
148
Generate within-page table of contents HTML.
149
150
Creates HTML for the page-level TOC showing section headings
151
and subsections within the current document.
152
153
Parameters:
154
- kind (str): Output format type (default: "html")
155
156
Returns:
157
str: HTML string for page TOC
158
"""
159
160
def navbar_align_class() -> str:
161
"""
162
Return navbar alignment CSS classes based on theme configuration.
163
164
Determines the appropriate Bootstrap classes for navbar alignment
165
based on the theme_navbar_align configuration option.
166
167
Returns:
168
str: CSS class string for navbar alignment
169
"""
170
```
171
172
### Utility Functions
173
174
Additional utility functions for TOC processing:
175
176
```python { .api }
177
def add_collapse_checkboxes(soup: BeautifulSoup) -> None:
178
"""
179
Add collapsible functionality to toctrees.
180
181
Modifies toctree HTML to include collapse/expand checkboxes
182
for hierarchical navigation sections.
183
184
Parameters:
185
- soup (BeautifulSoup): Parsed HTML soup object to modify
186
"""
187
188
def get_nonroot_toctree(
189
app: Sphinx,
190
pagename: str,
191
ancestorname: str,
192
toctree,
193
**kwargs
194
) -> str:
195
"""
196
Get partial TocTree fragments for non-root pages.
197
198
Generates toctree HTML for specific sections of the document
199
hierarchy, useful for creating contextual navigation.
200
201
Parameters:
202
- app (Sphinx): Sphinx application instance
203
- pagename (str): Current page name
204
- ancestorname (str): Name of ancestor page to start from
205
- toctree: Toctree object
206
- **kwargs: Additional toctree options
207
208
Returns:
209
str: HTML string for partial toctree
210
"""
211
```
212
213
### Data Classes
214
215
```python { .api }
216
@dataclass
217
class LinkInfo:
218
"""
219
Information about navigation links in toctrees.
220
221
Attributes:
222
- is_current (bool): Whether this is the current page
223
- href (str): URL for the link
224
- title (str): Display title for the link
225
- is_external (bool): Whether link points to external site
226
"""
227
is_current: bool
228
href: str
229
title: str
230
is_external: bool
231
```
232
233
## Math in Headings
234
235
### Basic Math Support
236
237
```rst
238
Section Title with Math
239
=======================
240
241
Integration with :math:`\int_0^1 x^2 dx`
242
=========================================
243
244
Complex Equations
245
=================
246
247
The equation :math:`E = mc^2` demonstrates energy-mass equivalence.
248
249
Advanced Mathematics
250
====================
251
252
Quantum mechanics uses :math:`\hat{H}\psi = E\psi` as the fundamental equation.
253
```
254
255
### LaTeX Math Expressions
256
257
```rst
258
Mathematical Functions
259
======================
260
261
Fourier Transform: :math:`F(\omega) = \int_{-\infty}^{\infty} f(t) e^{-i\omega t} dt`
262
263
Matrix Operations
264
=================
265
266
Identity matrix: :math:`\mathbf{I} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}`
267
```
268
269
## Navigation Hierarchy
270
271
### Breadcrumb Navigation
272
273
The TOC processing enables breadcrumb navigation based on document hierarchy:
274
275
```python
276
# Generated breadcrumb context
277
breadcrumbs = [
278
{"title": "Home", "url": "/"},
279
{"title": "User Guide", "url": "/user-guide/"},
280
{"title": "Advanced Topics", "url": "/user-guide/advanced/"},
281
{"title": "Current Page", "url": "#"}
282
]
283
```
284
285
### Hierarchical Navigation
286
287
```rst
288
.. toctree::
289
:maxdepth: 2
290
:caption: Contents:
291
292
introduction
293
user-guide/index
294
api/index
295
examples/index
296
```
297
298
Results in structured navigation with proper ancestor relationships.
299
300
## TOC Configuration
301
302
### Basic TOC Settings
303
304
```python
305
# conf.py
306
html_theme_options = {
307
"show_toc_level": 2, # Depth of TOC display
308
"collapse_navigation": False, # Keep navigation expanded
309
"navigation_depth": 4, # Maximum navigation depth
310
}
311
```
312
313
### Advanced TOC Options
314
315
```python
316
# conf.py
317
html_theme_options = {
318
# TOC display options
319
"show_toc_level": 3,
320
"show_nav_level": 2,
321
322
# Navigation behavior
323
"collapse_navigation": True,
324
"sticky_navigation": True,
325
"includehidden": True,
326
327
# Sidebar TOC
328
"secondary_sidebar_items": ["page-toc", "edit-this-page"],
329
}
330
```
331
332
## Usage Examples
333
334
### Math in Section Titles
335
336
```rst
337
Mathematical Concepts
338
=====================
339
340
Linear Algebra: :math:`Ax = b`
341
-------------------------------
342
343
The fundamental equation of linear algebra.
344
345
Calculus: :math:`\frac{df}{dx}`
346
-------------------------------
347
348
Derivatives and their applications.
349
350
Statistics: :math:`\mu = \frac{1}{n}\sum_{i=1}^n x_i`
351
----------------------------------------------------
352
353
Mean calculation formula.
354
```
355
356
### Complex Document Structure
357
358
```rst
359
.. toctree::
360
:maxdepth: 3
361
:caption: Documentation
362
:hidden:
363
364
getting-started/index
365
user-guide/index
366
api-reference/index
367
examples/index
368
369
Mathematical Analysis
370
=====================
371
372
.. toctree::
373
:maxdepth: 2
374
375
analysis/calculus
376
analysis/linear-algebra
377
analysis/statistics
378
```
379
380
### Custom TOC Templates
381
382
```python
383
# conf.py - Custom TOC template
384
html_theme_options = {
385
"secondary_sidebar_items": ["custom-toc.html", "edit-this-page"]
386
}
387
```
388
389
```jinja2
390
{# custom-toc.html #}
391
<nav class="bd-toc" id="bd-toc-nav">
392
<ul class="visible nav section-nav flex-column">
393
{% for toctree in toctrees %}
394
{{ toctree }}
395
{% endfor %}
396
</ul>
397
</nav>
398
```
399
400
## Template Context Variables
401
402
The TOC processing adds these variables to template context:
403
404
- **toctree functions**: Custom navigation functions
405
- **ancestor_pages**: Page hierarchy information
406
- **breadcrumb_items**: Breadcrumb navigation data
407
- **math_enabled**: Whether math rendering is active
408
409
## Integration with MathJax
410
411
The math rendering integrates with Sphinx's MathJax configuration:
412
413
```python
414
# conf.py
415
extensions = ['sphinx.ext.mathjax']
416
417
mathjax3_config = {
418
'tex': {
419
'inlineMath': [['$', '$'], ['\\(', '\\)']],
420
'displayMath': [['$$', '$$'], ['\\[', '\\]']],
421
}
422
}
423
```
424
425
## Performance Considerations
426
427
- **Math rendering**: Only processes nodes containing math expressions
428
- **Hierarchy caching**: Page relationships are cached during build
429
- **Template optimization**: Functions are injected once per page render
430
431
## Error Handling
432
433
The TOC processing handles various edge cases:
434
435
- **Missing ancestors**: Graceful fallback to available hierarchy
436
- **Malformed math**: LaTeX errors are passed through to MathJax
437
- **Version compatibility**: Automatic detection of Sphinx version features
438
439
## Advanced Features
440
441
### Custom Navigation Functions
442
443
The injected functions provide advanced navigation capabilities:
444
445
```jinja2
446
{# Template usage examples #}
447
{{ get_nav_object(maxdepth=2, collapse=true) }}
448
{{ generate_breadcrumbs(pagename) }}
449
{{ render_toc_tree(include_hidden=false) }}
450
```
451
452
### Conditional TOC Display
453
454
```python
455
# conf.py - Conditional TOC based on page type
456
html_theme_options = {
457
"secondary_sidebar_items": {
458
"api/**": ["page-toc"], # API pages: only TOC
459
"examples/**": ["download-page"], # Examples: download links
460
"**": ["page-toc", "edit-this-page"] # Default: TOC + edit button
461
}
462
}
463
```