Skip to content

How to add an item to the table of contents? #7783

Answered by kamilkrzyskow
woter1832 asked this question in Q&A
Discussion options

You must be logged in to vote

A simple example without conditionals to limit it to the pages with comments, but should be enough to get you 80% there ✌️

from mkdocs.structure.toc import AnchorLink

def on_page_content(html, page, config, files):
    
    if not page.toc or not page.toc.items:
        return
        
    page.toc.items[0].children.append(AnchorLink("Comments", "comments", 2))

EDIT:
Apart of the default suggestion to use a comments true/false flag in the meta header and your addition below, there are also other conditionals you could want to use. Like the page.file.src_uri.startswith("blog/posts") which would include every post in the directory, or another option is page.meta.template == "blog-post.html"

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
5 replies
@kamilkrzyskow
Comment options

Answer selected by woter1832
@woter1832
Comment options

@kamilkrzyskow
Comment options

@woter1832
Comment options

@kamilkrzyskow
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants