Automatically link across pages in MkDocs.
With pip
:
python3 -m pip install mkdocs-autorefs
# mkdocs.yml
plugins:
- search
- autorefs
If a heading title that appears several times throughout the site, set the priority parameter to decide which page will be linked. The priority list follows the gitignore syntax and is tested in reverse: each anchor will be assigned the lowest priority amongst all of its matches.
# mkdocs.yml
plugins:
- search
- autorefs:
priority:
- '*' # priority to all files
- reference # except reference/... files
In one of your Markdown files (e.g. doc1.md
) create some headings:
## Hello, world!
## Another heading
Link to [Hello, World!](#hello-world) on the same page.
This is a normal link to an anchor. MkDocs generates anchors for each heading, and they can always be used to link to something, either within the same page (as shown here) or by specifying the path of the other page.
But with this plugin, you can link to a heading from any other page on the site without needing to know the path of either of the pages, just the heading title itself.
Let's create another Markdown page to try this, subdir/doc2.md
:
We can [link to that heading][hello-world] from another page too.
This works the same as [a normal link to that heading](../doc1.md#hello-world).
Linking to a heading without needing to know the destination page can be useful if specifying that path is cumbersome, e.g. when the pages have deeply nested paths, are far apart, or are moved around frequently. And the issue is somewhat exacerbated by the fact that MkDocs supports only relative links between pages.
mkdocs-autorefs requires Python 3.7 or above.
To install Python 3.7, I recommend using pyenv
.
# install pyenv
git clone https://github.com/pyenv/pyenv ~/.pyenv
# setup pyenv (you should also put these three lines in .bashrc or similar)
export PATH="${HOME}/.pyenv/bin:${PATH}"
export PYENV_ROOT="${HOME}/.pyenv"
eval "$(pyenv init -)"
# install Python 3.7
pyenv install 3.7.12
# make it available globally
pyenv global system 3.7.12