Download Links and TOC Demo¶
This notebook demonstrates how MkDocs-Jupyter generates download links and integrates with the table of contents.
Features Demonstrated¶
- Automatic download link generation
- TOC extraction from notebook headings
- Integration with MkDocs navigation
- Multi-level heading support
1. Download Link Feature¶
When include_source: true
is configured, MkDocs-Jupyter automatically adds a download link for the source notebook file. This allows users to:
- Download the
.ipynb
file directly - Open it in their local Jupyter environment
- Run and modify the code themselves
- Use it as a starting point for their own work
Benefits of Download Links¶
- Educational: Students can download and practice
- Reproducibility: Exact code can be re-run
- Collaboration: Easy sharing of notebooks
- Offline Access: Work without internet connection
# Example code that users can download and run
import numpy as np
import pandas as pd
# Create sample data
data = {
"Feature": ["Download Links", "TOC Integration", "Navigation", "Search"],
"Status": ["✓ Enabled", "✓ Enabled", "✓ Enabled", "✓ Enabled"],
"Description": [
"Automatic .ipynb download",
"Headings become TOC entries",
"Integrates with site nav",
"Content is searchable",
],
}
df = pd.DataFrame(data)
print("MkDocs-Jupyter Features:")
df
2. Table of Contents Integration¶
MkDocs-Jupyter automatically extracts headings from notebooks and integrates them into the page's table of contents.
How TOC Works¶
- Heading Extraction: All markdown headings are parsed
- Level Support: H1 through H6 are supported
- Automatic Anchors: Each heading gets an anchor link
- Navigation Integration: TOC appears in the sidebar
TOC Configuration¶
The TOC behavior is controlled by these settings:
plugins:
- mkdocs-jupyter:
toc_depth: 3 # Include up to H3 in TOC
enable_default_notebooks_toc: true
enable_default_jupyter_toc: true
# Demonstrate TOC structure programmatically
toc_structure = {
"Level 1": "Main sections (H1)",
"Level 2": "Subsections (H2)",
"Level 3": "Sub-subsections (H3)",
"Level 4": "May be excluded (H4)",
}
print("TOC Hierarchy:")
for level, description in toc_structure.items():
indent = " " * (int(level.split()[-1]) - 1)
print(f"{indent}• {level}: {description}")
3. Navigation Features¶
The TOC integrates with MkDocs Material theme features:
3.1 Sidebar Navigation¶
- TOC appears in the right sidebar
- Active section is highlighted
- Smooth scrolling to sections
- Collapsible sections for long documents
3.2 Mobile Navigation¶
On mobile devices:
- TOC moves to a drawer menu
- Touch-friendly navigation
- Responsive design
import matplotlib.patches as patches
# Visual representation of navigation flow
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
# Draw components
components = [
{"name": "Notebook\nHeadings", "pos": (1, 3), "color": "#4CAF50"},
{"name": "MkDocs\nJupyter", "pos": (3, 3), "color": "#2196F3"},
{"name": "Page\nTOC", "pos": (5, 3), "color": "#FF9800"},
{"name": "Site\nNavigation", "pos": (7, 3), "color": "#9C27B0"},
]
for comp in components:
rect = patches.FancyBboxPatch(
(comp["pos"][0] - 0.4, comp["pos"][1] - 0.3),
0.8,
0.6,
boxstyle="round,pad=0.1",
facecolor=comp["color"],
edgecolor="black",
alpha=0.8,
)
ax.add_patch(rect)
ax.text(
comp["pos"][0],
comp["pos"][1],
comp["name"],
ha="center",
va="center",
color="white",
fontweight="bold",
)
# Draw arrows
arrow_props = dict(arrowstyle="->", lw=2, color="gray")
ax.annotate("", xy=(2.6, 3), xytext=(1.4, 3), arrowprops=arrow_props)
ax.annotate("", xy=(4.6, 3), xytext=(3.4, 3), arrowprops=arrow_props)
ax.annotate("", xy=(6.6, 3), xytext=(5.4, 3), arrowprops=arrow_props)
# Labels
ax.text(2, 3.5, "Extract", ha="center", fontsize=10)
ax.text(4, 3.5, "Generate", ha="center", fontsize=10)
ax.text(6, 3.5, "Integrate", ha="center", fontsize=10)
ax.set_xlim(0, 8)
ax.set_ylim(2, 4)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("TOC Generation Flow", fontsize=14, fontweight="bold", pad=20)
plt.tight_layout()
plt.show()
4. Best Practices¶
4.1 Heading Structure¶
For optimal TOC generation:
- Use semantic heading hierarchy: Don't skip levels
- Keep headings concise: Long headings clutter the TOC
- Use descriptive text: Help users navigate
- Limit depth: 3 levels is usually sufficient
4.2 Download Considerations¶
When users download notebooks:
- Include dependencies: List required packages
- Use relative paths: For data files
- Add setup instructions: In the first cell
- Test offline execution: Ensure it works standalone
# Example: Setup cell for downloaded notebooks
"""
# Setup Instructions
To run this notebook locally, install required packages:
pip install pandas numpy matplotlib
Data files are available at: https://example.com/data
"""
# Package version info
import sys
print("Python version:", sys.version)
print("\nRequired packages:")
packages = ["pandas", "numpy", "matplotlib"]
for pkg in packages:
try:
module = __import__(pkg)
print(f" {pkg}: {module.__version__}")
except ImportError:
print(f" {pkg}: Not installed")
5. Advanced Features¶
5.1 Custom Download Behavior¶
You can customize download behavior:
extra:
notebook_download:
text: "Download Notebook" # Custom button text
icon: "material/download" # Custom icon
5.2 TOC Styling¶
The TOC can be styled with custom CSS:
.md-nav--secondary {
/* Custom TOC styles */
}
5.3 Programmatic TOC Access¶
You can access TOC data programmatically for custom navigation.
# Example: Generate a custom TOC summary
headings = [
("1. Download Link Feature", 2),
(" 1.1 Benefits of Download Links", 3),
("2. Table of Contents Integration", 2),
(" 2.1 How TOC Works", 3),
(" 2.2 TOC Configuration", 3),
("3. Navigation Features", 2),
("4. Best Practices", 2),
("5. Advanced Features", 2),
]
print("📑 Table of Contents Summary:")
print("=" * 40)
for heading, level in headings:
if level == 2:
print(f"\n{heading}")
else:
print(f"{heading}")
print("\n" + "=" * 40)
Summary¶
This notebook demonstrated:
✅ Download Links: Automatic generation with include_source: true
✅ TOC Integration: Headings automatically become navigation items
✅ Multi-level Support: Nested headings create hierarchical TOC
✅ Theme Integration: Works seamlessly with MkDocs Material
Users can now:
- Download notebooks for local use
- Navigate long notebooks easily
- Find content quickly
- Work offline with downloaded files
The combination of download links and TOC integration makes notebooks more accessible and user-friendly in documentation!