MkDocs Macros Plugin
The MkDocs Macros Plugin extends MkDocs with powerful templating capabilities, allowing users to define custom variables, macros, and filters using Python. It enables dynamic content generation within Markdown pages and integrates seamlessly with the MkDocs build process. The current version is 1.5.0, and it has a regular release cadence, with updates typically every few months.
Warnings
- breaking The syntax for declaring macros and filters within `define_env` changed significantly in version 0.3.0. Previously, `@macro` and `@filter` decorators were used directly. From 0.3.0 onwards, these were replaced by `@env.macro` and `@env.filter`.
- gotcha Older versions (<1.0.4) of `mkdocs-macros-plugin` could experience filter-related warnings or issues when used with `MkDocs >= 1.5`. This was due to changes in how MkDocs handled filters.
- gotcha In versions prior to 1.2.0, a `define_env()` function was implicitly required in your Python module even if you weren't defining custom macros or variables, leading to unexpected errors if omitted. This is no longer the case.
Install
-
pip install mkdocs-macros-plugin
Quickstart
mkdocs.yml:
plugins:
- search
- macros
# Optional: point to a custom directory for macros (default: 'docs/macros')
# custom_dir: my_macros_folder
my_macros_folder/main.py (or docs/main.py if no custom_dir):
def define_env(env):
"""
This is the hook for defining variables, macros and filters.
"""
# Define a simple variable
env.variables['project_name'] = 'My Awesome Project'
# Define a macro function
@env.macro
def hello(name='World'):
return f"Hello, {name}!"
# Define a Jinja2 filter
@env.filter
def capitalize_words(text):
return ' '.join(word.capitalize() for word in str(text).split())
Markdown example (e.g., index.md):
# Welcome to {{ project_name }}
This is a greeting: {{ hello('AI Agent') }}
Apply a filter: {{ 'hello world' | capitalize_words }}