MkDocs Macros Plugin

1.5.0 · active · verified Fri Apr 10

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

Install

Quickstart

To get started, add `macros` to your `plugins` list in `mkdocs.yml`. Then, create a Python file (e.g., `main.py` within your `docs` directory or a custom directory specified by `custom_dir`) containing a `define_env(env)` function. This function is the entry point for defining your custom variables, macros, and filters, which can then be used in your Markdown pages. Run `mkdocs serve` to see your changes.

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 }}

view raw JSON →