14
14
def add_toctree_functions (app , pagename , templatename , context , doctree ):
15
15
"""Add functions so Jinja templates can add toctree objects."""
16
16
17
- def generate_nav_html (kind , ** kwargs ):
17
+ def generate_nav_html (kind , startdepth = None , ** kwargs ):
18
18
"""
19
19
Return the navigation link structure in HTML. Arguments are passed
20
20
to Sphinx "toctree" function (context["toctree"] below).
@@ -27,6 +27,10 @@ def generate_nav_html(kind, **kwargs):
27
27
----------
28
28
kind : ["navbar", "sidebar", "raw"]
29
29
The kind of UI element this toctree is generated for.
30
+ startdepth : int
31
+ The level of the toctree at which to start. By default, for
32
+ the navbar uses the normal toctree (`startdepth=0`), and for
33
+ the sidebar starts from the second level (`startdepth=1`).
30
34
kwargs: passed to the Sphinx `toctree` template function.
31
35
32
36
Returns
@@ -37,6 +41,22 @@ def generate_nav_html(kind, **kwargs):
37
41
toc_sphinx = context ["toctree" ](** kwargs )
38
42
soup = bs (toc_sphinx , "html.parser" )
39
43
44
+ if startdepth is None :
45
+ startdepth = 1 if kind == "sidebar" else 0
46
+
47
+ # select the "active" subset of the navigation tree for the sidebar
48
+ if startdepth > 0 :
49
+ selector = " " .join (
50
+ [
51
+ "li.current.toctree-l{} ul" .format (i )
52
+ for i in range (1 , startdepth + 1 )
53
+ ]
54
+ )
55
+ subset = soup .select (selector )
56
+ if not subset :
57
+ return ""
58
+ soup = bs (str (subset [0 ]), "html.parser" )
59
+
40
60
# pair "current" with "active" since that's what we use w/ bootstrap
41
61
for li in soup ("li" , {"class" : "current" }):
42
62
li ["class" ].append ("active" )
@@ -54,13 +74,15 @@ def generate_nav_html(kind, **kwargs):
54
74
for li in soup ("li" ):
55
75
li ["class" ].append ("nav-item" )
56
76
li .find ("a" )["class" ].append ("nav-link" )
77
+ # only select li items (not eg captions)
57
78
out = "\n " .join ([ii .prettify () for ii in soup .find_all ("li" )])
58
79
59
80
elif kind == "sidebar" :
81
+ # Add bootstrap classes for first `ul` items
82
+ for ul in soup ("ul" , recursive = False ):
83
+ ul .attrs ["class" ] = ul .attrs .get ("class" , []) + ["nav" , "bd-sidenav" ]
60
84
61
- # Join all the top-level `li`s together for display
62
- current_lis = soup .select ("li.current.toctree-l1 li.toctree-l2" )
63
- out = "\n " .join ([ii .prettify () for ii in current_lis ])
85
+ out = soup .prettify ()
64
86
65
87
elif kind == "raw" :
66
88
out = soup
0 commit comments