Skip to content

Commit 50961ba

Browse files
committed
Add a mkdocs macro to link to the glossary
Now documentation, both in `docs/` or in the code, can link to glossary terms by just using `{{glossary("Term")}}`. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 412c55c commit 50961ba

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

docs/_scripts/macros.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# License: MIT
2+
# Copyright © 2023 Frequenz Energy-as-a-Service GmbH
3+
4+
"""This module defines macros for use in Markdown files."""
5+
6+
import pathlib
7+
8+
from markdown.extensions import toc
9+
from mkdocs_macros import plugin as macros
10+
11+
12+
def define_env(env: macros.MacrosPlugin) -> None:
13+
"""Define the hook to create macro functions for use in Markdown.
14+
15+
Args:
16+
env: The environment to define the macro functions in.
17+
"""
18+
19+
def _slugify(text: str) -> str:
20+
"""Slugify a text.
21+
22+
Args:
23+
text: The text to slugify.
24+
25+
Returns:
26+
The slugified text.
27+
"""
28+
# The type of the return value is not defined for the markdown library.
29+
# Also for some reason `mypy` thinks the `toc` module doesn't have a
30+
# `slugify_unicode` function, but it definitely does.
31+
return toc.slugify_unicode(text, "-") # type: ignore[attr-defined,no-any-return]
32+
33+
@env.macro # type: ignore[misc]
34+
def glossary(term: str) -> str:
35+
"""Create a link to the glossary entry for the given term.
36+
37+
Args:
38+
term: The term to link to.
39+
40+
Returns:
41+
The Markdown link to the glossary entry for the given term.
42+
"""
43+
current_path = pathlib.Path(env.page.file.src_uri)
44+
glossary_path = pathlib.Path("intro/glossary.md")
45+
link_path = glossary_path.relative_to(current_path.parent)
46+
return f"[{term}]({link_path}#{_slugify(term)})"

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ plugins:
8989
- literate-nav:
9090
nav_file: SUMMARY.md
9191
- macros:
92+
module_name: docs/_scripts/macros
9293
on_undefined: strict
9394
on_error_fail: true
9495
- mike:

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ module = [
177177
"async_solipsism.*",
178178
"grpc.aio",
179179
"grpc.aio.*",
180+
"mkdocs_macros.*",
180181
# There is a stubs package available, but it's not working:
181182
# https://github.com/eggplants/networkx-stubs/issues/1
182183
"networkx",

0 commit comments

Comments
 (0)