diff --git a/docs/notes/mkdocs-conditionally-hide-toc.md b/docs/notes/mkdocs-conditionally-hide-toc.md new file mode 100644 index 0000000..ef88030 --- /dev/null +++ b/docs/notes/mkdocs-conditionally-hide-toc.md @@ -0,0 +1,13 @@ +--- +title: Hide short Table of Contents +tags: + - Mkdocs +--- + +Some of my notes don't have headings. Others have barely any. However, the Table of Contents area takes up a large area of screen for no reason. + +This hook only shows the Table of Contents area when there are more than 4 headings (at any level). + +```python +{! ../hooks/hide_toc.py !} +``` diff --git a/hooks/hide_toc.py b/hooks/hide_toc.py new file mode 100644 index 0000000..47b6810 --- /dev/null +++ b/hooks/hide_toc.py @@ -0,0 +1,19 @@ +from mkdocs.structure.toc import TableOfContents + +def flatten_toc(item): + yield item + children = item.items if isinstance(item, TableOfContents) else item.children + for subitem in children: + yield from flatten_toc(subitem) + + +def on_page_content(html, page, config, files): + if not page.url.startswith("notes/") or page.file.src_uri == "notes/index.md": + return + + toc = list(flatten_toc(page.toc)) + + if len(toc) <= 4: + hidden_items = page.meta.setdefault("hide", []) + if "toc" not in hidden_items: + hidden_items.append("toc") diff --git a/mkdocs.yml b/mkdocs.yml index dd9c464..a80b400 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -55,6 +55,7 @@ theme: hooks: - hooks/notes.py - hooks/tag_nav.py + - hooks/hide_toc.py # Extensions markdown_extensions: