Unleash the power of MkDocs with macros and variables
npx @tessl/cli install tessl/pypi-mkdocs-macros-plugin@1.3.00
# MkDocs Macros Plugin
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: mkdocs-macros-plugin
7
- **Language**: Python
8
- **Installation**: `pip install mkdocs-macros-plugin`
9
10
## Core Imports
11
12
```python
13
from mkdocs_macros import fix_url, is_relative_url
14
```
15
16
Note: `is_relative_url` is an alias for the `is_relative` function.
17
18
For plugin usage, configure in `mkdocs.yml`:
19
20
```yaml
21
plugins:
22
- macros
23
```
24
25
## Basic Usage
26
27
### Configuration
28
29
Basic `mkdocs.yml` configuration:
30
31
```yaml
32
plugins:
33
- macros:
34
module_name: main # optional, default is 'main'
35
include_dir: includes # optional directory for templates
36
include_yaml:
37
- data/variables.yml
38
verbose: true # optional debug output
39
```
40
41
### Module Definition
42
43
Create `main.py` in your project root:
44
45
```python
46
def define_env(env):
47
"""
48
Define variables, macros, and filters for use in templates
49
"""
50
# Add variables
51
env.variables['project_version'] = '1.0.0'
52
53
# Define macros using decorator
54
@env.macro
55
def button(label, url):
56
return f'<a class="md-button" href="{url}">{label}</a>'
57
58
# Define filters using decorator
59
@env.filter
60
def reverse_string(text):
61
return text[::-1]
62
```
63
64
### Template Usage
65
66
In your markdown files:
67
68
```markdown
69
Project version: {{ project_version }}
70
71
{{ button('Click me', 'https://example.com') }}
72
73
{% if config.site_name %}
74
Site name is: {{ config.site_name }}
75
{% endif %}
76
77
{{ "Hello World" | reverse_string }}
78
```
79
80
## Architecture
81
82
The plugin operates through several key components:
83
84
- **MacrosPlugin**: Core MkDocs plugin class that manages configuration, template environment, and rendering
85
- **Template Variables**: Built-in and custom variables accessible in Jinja2 templates
86
- **Module System**: Python modules that define custom macros, filters, and variables
87
- **Hook System**: Pre/post processing hooks for advanced customization
88
- **Pluglet System**: Installable modules distributed via PyPI for shared functionality
89
90
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.
91
92
## Capabilities
93
94
### Plugin Configuration
95
96
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.
97
98
```yaml { .api }
99
# Configuration in mkdocs.yml under plugins: - macros:
100
module_name: 'main' # Python module filename for macros
101
modules: [] # List of pre-installed modules (pluglets)
102
render_by_default: true # Render pages by default vs opt-in
103
force_render_paths: '' # Pathspec patterns to force rendering
104
include_dir: '' # Directory for {% include %} and {% import %}
105
include_yaml: [] # Additional YAML files to load
106
j2_block_start_string: '' # Custom Jinja2 block start marker
107
j2_block_end_string: '' # Custom Jinja2 block end marker
108
j2_variable_start_string: '' # Custom Jinja2 variable start marker
109
j2_variable_end_string: '' # Custom Jinja2 variable end marker
110
j2_comment_start_string: '' # Custom Jinja2 comment start marker
111
j2_comment_end_string: '' # Custom Jinja2 comment end marker
112
on_undefined: 'keep' # Behavior for undefined variables
113
on_error_fail: false # Exit on rendering errors in CI/CD
114
verbose: false # Enable verbose logging
115
```
116
117
[Plugin Configuration](./plugin-configuration.md)
118
119
### Module Definition Interface
120
121
Interface for defining custom variables, macros, and filters in Python modules. Provides the primary extension mechanism for adding functionality to the template environment.
122
123
```python { .api }
124
def define_env(env):
125
"""Primary hook for module definition"""
126
127
def on_pre_page_macros(env):
128
"""Optional hook called before macro rendering"""
129
130
def on_post_page_macros(env):
131
"""Optional hook called after macro rendering"""
132
133
def on_post_build(env):
134
"""Optional hook called after site build"""
135
```
136
137
[Module System](./module-system.md)
138
139
### Template Environment
140
141
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.
142
143
```python { .api }
144
class MacrosPlugin:
145
# Template environment properties
146
@property
147
def variables(self) -> dict: ...
148
@property
149
def macros(self) -> dict: ...
150
@property
151
def filters(self) -> dict: ...
152
@property
153
def env(self) -> Environment: ...
154
155
# Registration methods
156
def macro(self, function, name: str = '') -> callable: ...
157
def filter(self, function, name: str = '') -> callable: ...
158
159
# Rendering methods
160
def render(self, markdown: str, force_rendering: bool = False) -> str: ...
161
def has_j2(self, s: str) -> bool: ...
162
```
163
164
[Template Environment](./template-environment.md)
165
166
### Built-in Variables and Context
167
168
Predefined variables and context objects automatically available in templates, including environment information, git data, page metadata, and site configuration.
169
170
```python { .api }
171
# Built-in template variables
172
environment: dict # System and version information
173
plugin: dict # Plugin configuration
174
git: dict # Git repository information
175
config: dict # Complete MkDocs configuration
176
page: object # Current page metadata
177
navigation: object # Site navigation structure
178
files: object # Site file collection
179
```
180
181
[Built-in Context](./built-in-context.md)
182
183
### Built-in Macros and Filters
184
185
Default macros and filters provided by the plugin for common templating tasks, documentation generation, and utility functions.
186
187
```python { .api }
188
def context(obj: dict = None) -> list: ...
189
def macros_info() -> str: ...
190
def now() -> datetime: ...
191
def fix_url(url: str) -> str: ...
192
193
def pretty(var_list: list) -> str: ...
194
def relative_url(path: str) -> str: ...
195
```
196
197
[Built-in Functions](./built-in-functions.md)
198
199
### External Integration
200
201
Methods for integrating with other MkDocs plugins and external systems, including registration hooks and debugging utilities.
202
203
```python { .api }
204
class MacrosPlugin:
205
# External registration methods
206
def register_macros(self, items: dict): ...
207
def register_filters(self, items: dict): ...
208
def register_variables(self, items: dict): ...
209
210
# Debug and utility methods
211
def start_chatting(self, prefix: str, color: str = 'yellow') -> callable: ...
212
def force_page_rendering(self, filename: str) -> bool: ...
213
```
214
215
[External Integration](./external-integration.md)
216
217
## Types
218
219
```python { .api }
220
from typing import Dict, List, Union, Any, Callable
221
from jinja2 import Environment
222
from mkdocs.structure.pages import Page
223
from mkdocs.structure.nav import Navigation
224
from mkdocs.structure.files import Files
225
from mkdocs.config.config_options import Config
226
from datetime import datetime
227
228
# Plugin configuration type hints
229
PluginConfig = Dict[str, Any]
230
231
# Template function signatures
232
MacroFunction = Callable[..., str]
233
FilterFunction = Callable[[Any], Any]
234
HookFunction = Callable[["MacrosPlugin"], None]
235
236
# Built-in variable types
237
EnvironmentInfo = Dict[str, str]
238
GitInfo = Dict[str, Union[str, datetime, bool]]
239
PageInfo = Page
240
NavigationInfo = Navigation
241
FilesInfo = Files
242
ConfigInfo = Config
243
```