Skip to content

MkNavs

A quick overview

All elements which can become part of the "website tree" inherit from MkNode

Simplified, there are basically 3 different MkNode types:

  • MkNavs, used to structure the pages into a hierarchy
  • Mkpages, used as a container for the markdown elements
  • MkNode elements, used to display the markdown itself (and in some cases HTML)

Given a random Element from a full website tree, this is how the path from root to leaf element could look like:

graph LR
  c058d3b["Root nav
  (MkNav)"]
  b343f32["Sub-nav
  (MkNav)"]
  9308f79["Page
  (MkPage)"]
  c049bd5["Container element
  (MkTabbed)"]
  042e872["Container element
  (MkAdmonition)"]
  251098c["Atomic markdown element
  (MkText)"]
  c058d3b --> b343f32
  b343f32 --> 9308f79
  9308f79 --> c049bd5
  c049bd5 --> 042e872
  042e872 --> 251098c

In essence: A path can contain one or more MkNavs, exactly one MkPage, and one or more (nested) MkNode Elements.

Info

Because of the Markdown elements being part of the tree, the elements can behave quite intelligently in some situations. For example, code blocks automatically set the correct amount of fence backticks. That way you cant get conflicts because of two blocks having the same fence backtick sequence. The same accounts for the new Block extensions from pymdownx, which uses / as fence character.

MkNavs: General information

MkNavs are nodes to represent "sections", perhaps comparable to a folder (with MkPages being files in this analogy). MkNavs can contain other MkNavs to construct a hierarchical website tree structure, as well as MkPages and MkLinks. MkPages can be "regular" child of an MkNav, or an index page. Index pages are dedicated pages which are shown when a site nav menu item containing children is clicked, or for the website root.

Theme support for index pages

Index pages need specific theme support (like MkDocs-Material has) or the mkdocs-section-index plugin.

MkNav metadata

MkNavs (as well as MkPages) own a metadata object, which can be set via the MkPage.metadata attribute. That metadata is not really useful for the MkNav itself. The metadata gets propagated to the child pages though, and thus this mechanism can be helpful to set metadata for a complete website branch / section in one go. Metadata is also inherited from the parent MkNavs in case they have metadata set. In other words: Template / Metadata inheritance happens through the whole chain of MkNavs / MkPages, from top to bottom.

Further info

See the Metadata section, the MkDocs Documentation as well as the MkDocs-Material docs for further info.

MkNav templates

Similar to metadata, page templates can also be set for MkNavs. (small difference: attribute is called page_template for MkNavs instead of template for MkPages) Again, they are not used by the MkNavs itself, but propagate to all child pages / navs. You will find more details in later parts of the docs.

Here is a quick example to show how easy a new template can get set up. Compare this one-liner to the "regular" process of creating an HTML file (with no markdown support) in a subfolder separated from your actual content:

nav = MkNav()
nav.page_template.announce.content = "Display **Markdown** in announcement bar!"

In the case of MkDocs, Template HTMLs will get created temporarily during the build process and will get deleted after deployment / serving.

Static templates

Apart from "page templates", which apply to specific (groups of) MkPages, there are also "static" templates which are part of the Theme object (or of a Theme subclass). That way you can for example populate the 404 error page easily with Markdown.

Using MkNavs

The very first element you get in MkNodes is the root nav. The root nav is the node which will contain all other nodes at the end of the tree building process, in a nested, hierarchical structure.

Technically, there are no differences between the root MkNav and any other "nested" MkNav, except that the root MkNav does not have a parent.

You can construct sub-MkNavs by instantiating them, by using MkNav.add_nav or by using the decorator routing mechanism.

Besides getting created via decorated functions, MkNavs can also get populated via decorators.

nav = MkNav()  # this nav will get populated with a sub-nav

@nav.route.nav("Path to", "Nav", optional=kw_args):  # Arguments reflect the "path" of newly created nav.
def _(sub_nav: MkNav)  # naming these methods is rather pointless, so we'll just call them "_".
    sub_nav += ...  #  this sub_nav is created via decorator


@nav.route.page("My page"):  # Pages can get routed, too, of course.
...

Another way to populate MkNavs is by using the NavParser (parse attribute of an MkNav) The NavParser allows to read SUMMARY.md files (known from mkdocs-literate-nav ), "pure" markdown-file / folder structures and more. There is also an experimental support for index.py routing files as a replacement for SUMMARY.md files.

nav = MkNav()  # this nav will get populated with the *SUMMARY.md* content
nav.parse.file("path/to/SUMMARY.md")

Index pages

"Index pages" (the index.md files of the root and the subfolders) are a special case when it comes to building the tree. Each MkNav has a dedicated slot for an index page.

nav.index_page = my_mkpage_instance

Alternatively, MkNav.add_page takes the keyword argument is_index:

index_page = nav.add_page(is_index=True, ...)

Build process

During the build process, MkNavs get converted to SUMMARY.md files. These will then get picked up by MkDocs afterwards in order to build the MkDocs nav tree.

Info

In the future, MkNavs (as well as MkPages) will likely get converted to MkDocs.structure instances directly without taking the extra route of becoming a physical file on the hard drive.

Subclasses

MkNodes also contains a special subclass of MkNav called MkDoc. This node is responsible for creating API documentation in an easy way, using templates (to get in impression, this is the default template for documenting classes ). MkDoc objects have methods to collect submodules / classes from the module you want to document. The collected modules / classes are passed through the template render process in order to create Markdown text. That text will get added automatically to the MkDoc nav as an MkPage.

Every class gets exactly one page, nested below the module defining it: with section_name="API", module pkg.sub ends up at API/sub/ and its class Klass at API/sub/Klass/. Modules which only re-export a class (like a package __init__ with __all__) list it with a link to that page. Private modules (_impl) get no pages of their own, their public classes are documented where they are re-exported (or in the nearest public parent module).

API

mknodes.MkNav

Bases: MkNode

Nav section, representing a nestable menu.

A nav is named (exception is the root nav, which has section name = None), has an associated virtual file (in general a SUMMARY.md), an optional index page and can contain other navs as well as pages and links.

index_page property writable

index_page: MkPage | None

Get the current index page if set.

metadata instance-attribute

metadata = metadata_.Metadata(metadata or {})

Page Metadata.

nav instance-attribute

nav = navigation.Navigation()

Navigation object containing all child items.

parse instance-attribute

parse = navparser.NavParser(self)

Parser object used to build Navs from different data / directory structures.

resolved_file_path property

resolved_file_path: str

Returns the resulting section/subsection/../filename.xyz path.

route instance-attribute

route = navrouter.NavRouter(self)

Router used for decorator routing.

__add__

__add__(other: NavSubType) -> Self

Use this to to register MkNodes.

__init__

__init__(
    section: str | None = None,
    *,
    filename: str = "SUMMARY.md",
    metadata: dict[str, Any] | None = None,
    **kwargs: Any
) -> None

Constructor.

Parameters:

Name Type Description Default
section str | None

Section name for the Nav

None
filename str

FileName for the resulting nav

'SUMMARY.md'
metadata dict[str, Any] | None

Metadata for the nav. Child pages will inherit this.

None
kwargs Any

Keyword arguments passed to parent

{}

add_doc

add_doc(
    module: ModuleType | Sequence[str] | str | None = None,
    *,
    filter_by___all__: bool = False,
    recursive: bool = False,
    section_name: str | None = None,
    class_template: str | None = None,
    module_template: str | None = None,
    flatten_nav: bool = False
) -> MkDoc

Add a module documentation to the Nav.

Parameters:

Name Type Description Default
module ModuleType | Sequence[str] | str | None

The module to create a documentation section for.

None
filter_by___all__ bool

Whether the documentation

False
recursive bool

Whether to search modules recursively

False
section_name str | None

Override the name for the menu (default: module name)

None
class_template str | None

Override for the default ClassPage template

None
module_template str | None

Override for the default ModulePage template

None
flatten_nav bool

Whether classes should be put into top-level of the nav

False

add_nav

add_nav(section: str) -> MkNav

Create a Sub-Nav, register it to given Nav and return it.

Parameters:

Name Type Description Default
section str

Name of the new nav.

required

add_page

add_page(
    title: str | None = None,
    *,
    is_index: bool = False,
    is_homepage: bool = False,
    path: str | None = None,
    hide: list[str] | str | None = None,
    search_boost: float | None = None,
    exclude_from_search: bool | None = None,
    icon: str | None = None,
    status: PageStatusStr | None = None,
    subtitle: str | None = None,
    description: str | None = None,
    template: str | None = None,
    tags: list[str] | None = None
) -> MkPage

Add a page to the Nav.

Parameters:

Name Type Description Default
title str | None

Page title

None
is_index bool

Whether the page should become the index page.

False
is_homepage bool

Whether the page should become the homepage.

False
path str | None

optional path override

None
hide list[str] | str | None

Hide parts of the page ("toc", "nav", "path")

None
search_boost float | None

multiplier for search ranking

None
exclude_from_search bool | None

Exclude page from search index

None
icon str | None

optional page icon

None
status PageStatusStr | None

Page status

None
subtitle str | None

Page subtitle

None
description str | None

Page description

None
template str | None

Page template

None
tags list[str] | None

tags to show above the main headline and within the search preview

None

get_children

get_children() -> list[NavSubType]

Return all child items from the navigation.

to_markdown

to_markdown(flavor: str | Renderer | None = None) -> str

Return the nav as literate-nav Markdown (the same for every flavour).

mknodes.navs.navparser.NavParser

Class used for constructing MkNavs.

__init__

__init__(nav: MkNav) -> None

Constructor.

Parameters:

Name Type Description Default
nav MkNav

MkNav to use for routing

required

file

file(path: str | PathLike[str], **kwargs: Any) -> MkNav

Load an existing SUMMARY.md style file.

For each indentation level in SUMMARY.md, a new sub-nav is created.

Should support all SUMMARY.md options except wildcards.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the file

required
kwargs Any

Keyword arguments passed to the pages to create. Can be used to hide the TOC for all pages for example.

{}

folder

folder(folder: str | PathLike[str], *, recursive: bool = True, **kwargs: Any) -> MkNav

Load a MkNav tree from a folder.

This method creates a navigation structure based on the contents of a specified folder. It processes Markdown (.md) and HTML (.html) files, creating a hierarchical navigation tree that reflects the folder structure.

Specific behaviors: - SUMMARY.md files are ignored. - index.md files become index pages for their respective folders. - Hidden folders (starting with '.' or '_') are ignored. - Page titles can be overridden using page metadata.

Parameters:

Name Type Description Default
folder str | PathLike[str]

The folder to load .md and .html files from.

required
recursive bool

Whether to include all files recursively from subfolders.

True
**kwargs Any

Additional keyword arguments passed to the created pages. Can be used to set global page properties, e.g., hiding TOC.

{}

Examples:

parser = NavParser(my_nav)
folder_nav = parser.folder("docs/", recursive=True, toc=False)

json

json(obj: list[Any] | dict[str, str | list[Any] | dict[str, Any]]) -> None

Parse given list or dict and attach it to given MkNav.

If no Nav is given, create a new one Args: obj: Dictionary / List to parse

module

module(module: str | PathLike[str], *, recursive: bool = True, **kwargs: Any) -> MkNav

Load a MkNav tree from a Module.

This method creates a navigation structure from a given module. It iterates through the module's directory, creating pages for Python files and sub-navigations for subdirectories. Each Python file is displayed as a page with its content in a code box.

Parameters:

Name Type Description Default
module str | PathLike[str]

The module to load code files from. Can be a string path or a PathLike object.

required
recursive bool

Whether to include all files recursively.

True
**kwargs Any

Additional keyword arguments passed to the pages being created. These can be used to customize page properties, e.g., hiding the TOC.

{}
Example
parser = NavParser()
nav = parser.module("mknodes", recursive=True, hide_toc=True)

text

text(text: str, path: Path, **kwargs: Any) -> MkNav

Create a nav based on a SUMMARY.md-style list, given as text.

This method parses a text input formatted similar to a SUMMARY.md file and creates a navigation structure based on it. For each indentation level in the input text, a new sub-nav is created. The method supports all SUMMARY.md options except wildcards.

The method processes three main patterns in the input text: 1. Section and folder: Creates a subnav from a SUMMARY.md or index.py file. 2. Section and file: Creates a page or a subnav with an index page. 3. Section only: Creates a subnav from the indented lines following it.

Parameters:

Name Type Description Default
text str

The input text to parse, formatted like a SUMMARY.md file.

required
path Path

The path of the file containing the input text.

required
**kwargs Any

Additional keyword arguments passed to the pages to create. Can be used to set common properties for all pages.

{}

Examples:

parser = NavParser(nav)
text = '''
* [Section 1](folder1/)
* [Page 1](page1.md)
* Section 2/
    * [Subpage 1](subpage1.md)
    * [Subpage 2](subpage2.md)
'''
updated_nav = parser.text(text, pathlib.Path("path/to/file"))

mknodes.MkDoc

Bases: MkNav

Nav for showing a module documentation.

Every class gets exactly one page, below the module defining it (pkg.sub.Klass -> <section>/sub/Klass/), modules re-exporting it link to that page. With recursive=True, public submodules get their own (nested) MkDoc navs.

scope property

scope: ApiScope | None

The computed API scope (shared by all MkDocs of the tree).

__init__

__init__(
    module: ModuleType | Sequence[str] | str | None = None,
    *,
    filter_by___all__: bool = True,
    exclude_modules: list[str] | None = None,
    section_name: str | None = None,
    recursive: bool = False,
    class_template: str | None = None,
    module_template: str | None = None,
    flatten_nav: bool = False,
    **kwargs: Any
) -> None

Constructor.

Parameters:

Name Type Description Default
module ModuleType | Sequence[str] | str | None

Module to document

None
filter_by___all__ bool

Whether to filter stuff according to "all"

True
recursive bool

Whether to add navs for submodules (recursively)

False
exclude_modules list[str] | None

Modules to exclude (dotted path or module name)

None
section_name str | None

Optional section title override

None
class_template str | None

Override for the default ClassPage template

None
module_template str | None

Override for the default ModulePage template

None
flatten_nav bool

Deprecated, has no effect. Class pages are always listed in the nav of the module defining them.

False
kwargs Any

Keyword arguments passed to parent

{}

add_class_page

add_class_page(
    klass: type,
    *,
    find_topmost: bool = True,
    flatten: bool = False,
    path: str | None = None,
    **kwargs: Any
) -> MkClassPage

Add a page showing information about a class to this nav.

Links to the class (class tables, base classes, ...) point to this page.

Parameters:

Name Type Description Default
klass type

klass to build a page for

required
find_topmost bool

Deprecated, has no effect. The mkdocstrings directive always uses the path of the defining module.

True
flatten bool

Deprecated, has no effect. Class pages always get listed in the nav of the module they belong to.

False
path str | None

Page name (file stem). Defaults to the class name.

None
kwargs Any

keyword arguments passed to MkClassPage

{}

get_children

get_children()

Return computed children for module documentation.

Class pages are put below the module defining the class, so the URL of class Klass of module pkg.sub is <section>/sub/Klass/, the module page is <section>/sub/. See mknodes.navs.apiscope for the rules.