or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

built-in-context.mdbuilt-in-functions.mdexternal-integration.mdindex.mdmodule-system.mdplugin-configuration.mdtemplate-environment.md
tile.json

tessl/pypi-mkdocs-macros-plugin

Unleash the power of MkDocs with macros and variables

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/mkdocs-macros-plugin@1.3.x

To install, run

npx @tessl/cli install tessl/pypi-mkdocs-macros-plugin@1.3.0

index.mddocs/

MkDocs Macros Plugin

Unleash the power of MkDocs with macros and variables. A general-purpose plugin that transforms markdown pages into Jinja2 templates using variables, macros (functions), and custom filters, enabling contributors to produce richer and more beautiful documentation pages by leveraging Python functionality within markdown.

Package Information

  • Package Name: mkdocs-macros-plugin
  • Language: Python
  • Installation: pip install mkdocs-macros-plugin

Core Imports

from mkdocs_macros import fix_url, is_relative_url

Note: is_relative_url is an alias for the is_relative function.

For plugin usage, configure in mkdocs.yml:

plugins:
  - macros

Basic Usage

Configuration

Basic mkdocs.yml configuration:

plugins:
  - macros:
      module_name: main  # optional, default is 'main'
      include_dir: includes  # optional directory for templates
      include_yaml:
        - data/variables.yml
      verbose: true  # optional debug output

Module Definition

Create main.py in your project root:

def define_env(env):
    """
    Define variables, macros, and filters for use in templates
    """
    # Add variables
    env.variables['project_version'] = '1.0.0'
    
    # Define macros using decorator
    @env.macro
    def button(label, url):
        return f'<a class="md-button" href="{url}">{label}</a>'
    
    # Define filters using decorator  
    @env.filter
    def reverse_string(text):
        return text[::-1]

Template Usage

In your markdown files:

Project version: {{ project_version }}

{{ button('Click me', 'https://example.com') }}

{% if config.site_name %}
Site name is: {{ config.site_name }}
{% endif %}

{{ "Hello World" | reverse_string }}

Architecture

The plugin operates through several key components:

  • MacrosPlugin: Core MkDocs plugin class that manages configuration, template environment, and rendering
  • Template Variables: Built-in and custom variables accessible in Jinja2 templates
  • Module System: Python modules that define custom macros, filters, and variables
  • Hook System: Pre/post processing hooks for advanced customization
  • Pluglet System: Installable modules distributed via PyPI for shared functionality

The plugin integrates with MkDocs' build pipeline, rendering pages during the on_page_markdown event while providing access to site configuration, navigation, and page metadata.

Capabilities

Plugin Configuration

Configuration options for controlling plugin behavior, template rendering, Jinja2 settings, and module loading. These settings are defined in the mkdocs.yml file under the macros plugin section.

# Configuration in mkdocs.yml under plugins: - macros:
module_name: 'main'                # Python module filename for macros
modules: []                        # List of pre-installed modules (pluglets)
render_by_default: true           # Render pages by default vs opt-in
force_render_paths: ''            # Pathspec patterns to force rendering
include_dir: ''                   # Directory for {% include %} and {% import %}
include_yaml: []                  # Additional YAML files to load
j2_block_start_string: ''         # Custom Jinja2 block start marker
j2_block_end_string: ''           # Custom Jinja2 block end marker
j2_variable_start_string: ''      # Custom Jinja2 variable start marker
j2_variable_end_string: ''        # Custom Jinja2 variable end marker
j2_comment_start_string: ''       # Custom Jinja2 comment start marker
j2_comment_end_string: ''         # Custom Jinja2 comment end marker
on_undefined: 'keep'              # Behavior for undefined variables
on_error_fail: false              # Exit on rendering errors in CI/CD
verbose: false                    # Enable verbose logging

Plugin Configuration

Module Definition Interface

Interface for defining custom variables, macros, and filters in Python modules. Provides the primary extension mechanism for adding functionality to the template environment.

def define_env(env):
    """Primary hook for module definition"""

def on_pre_page_macros(env):
    """Optional hook called before macro rendering"""

def on_post_page_macros(env):
    """Optional hook called after macro rendering"""

def on_post_build(env):
    """Optional hook called after site build"""

Module System

Template Environment

Core template environment providing access to variables, macros, filters, and rendering capabilities. The environment object is the primary interface for interacting with the plugin from within modules and templates.

class MacrosPlugin:
    # Template environment properties
    @property
    def variables(self) -> dict: ...
    @property
    def macros(self) -> dict: ...
    @property
    def filters(self) -> dict: ...
    @property
    def env(self) -> Environment: ...
    
    # Registration methods
    def macro(self, function, name: str = '') -> callable: ...
    def filter(self, function, name: str = '') -> callable: ...
    
    # Rendering methods  
    def render(self, markdown: str, force_rendering: bool = False) -> str: ...
    def has_j2(self, s: str) -> bool: ...

Template Environment

Built-in Variables and Context

Predefined variables and context objects automatically available in templates, including environment information, git data, page metadata, and site configuration.

# Built-in template variables
environment: dict  # System and version information
plugin: dict      # Plugin configuration
git: dict         # Git repository information
config: dict      # Complete MkDocs configuration
page: object      # Current page metadata
navigation: object  # Site navigation structure
files: object     # Site file collection

Built-in Context

Built-in Macros and Filters

Default macros and filters provided by the plugin for common templating tasks, documentation generation, and utility functions.

def context(obj: dict = None) -> list: ...
def macros_info() -> str: ...
def now() -> datetime: ...
def fix_url(url: str) -> str: ...

def pretty(var_list: list) -> str: ...
def relative_url(path: str) -> str: ...

Built-in Functions

External Integration

Methods for integrating with other MkDocs plugins and external systems, including registration hooks and debugging utilities.

class MacrosPlugin:
    # External registration methods
    def register_macros(self, items: dict): ...
    def register_filters(self, items: dict): ...
    def register_variables(self, items: dict): ...
    
    # Debug and utility methods
    def start_chatting(self, prefix: str, color: str = 'yellow') -> callable: ...
    def force_page_rendering(self, filename: str) -> bool: ...

External Integration

Types

from typing import Dict, List, Union, Any, Callable
from jinja2 import Environment
from mkdocs.structure.pages import Page
from mkdocs.structure.nav import Navigation
from mkdocs.structure.files import Files
from mkdocs.config.config_options import Config
from datetime import datetime

# Plugin configuration type hints
PluginConfig = Dict[str, Any]

# Template function signatures
MacroFunction = Callable[..., str]
FilterFunction = Callable[[Any], Any]
HookFunction = Callable[["MacrosPlugin"], None]

# Built-in variable types
EnvironmentInfo = Dict[str, str]
GitInfo = Dict[str, Union[str, datetime, bool]]
PageInfo = Page
NavigationInfo = Navigation
FilesInfo = Files
ConfigInfo = Config