* variables do not work in snippets included using Snippets extension * workaround: use macros plugin to define snippets (as described here https://mkdocs-macros-plugin.readthedocs.io/en/latest/advanced/#including-snippets-in-pages)
3.2 KiB
template |
---|
overrides/main.html |
Variables
Macros and variables are powerful tools to parametrize Markdown files, as they
allow to perform Jinja templating directly from Markdown. This is especially
useful to include technical data from other files and add central variables via
mkdocs.yml
.
Configuration
Macros
The macros plugin adds support to reference variables and call macros and
supports Jinja templating directly from Markdown. It can be installed with
pip
:
pip install mkdocs-macros-plugin
Then, add the following to mkdocs.yml
:
plugins:
- macros
Usage
Using predefined variables
A set of predefined variables is enabled by default and can be used from
Markdown, including data from mkdocs.yml
. More specifically, predefined
variables fall into the following categories:
config.*
: configuration parameters frommkdocs.yml
page.*
: metadata and content of current pagenavigation.*
: list of all pages and sectionsenvironment.*
: underlying operating systemgit.*
: git-related information, if available
Example:
Welcome to {{ config.site_name }}!
Result:
Welcome to Material for MkDocs!
A list of all predefined variables can be printed with:
{{ macros_info() }}
Using custom variables
All data defined under extra
in mkdocs.yml
is automatically exposed as a
variable and can be used from the template. This enables centralized parameter
storage and management.
Example:
=== "docs/page.md"
```` markdown
The unit price is {{ unit.price }}
````
=== "mkdocs.yml"
``` yaml
extra:
unit:
price: 12.50
```
Result:
The unit price is 12.50.
Using variables in snippets
You may want to use variables in snippets, for example, when describing the same procedure in multiple contexts where only one piece of information differs. This does not work with snippets that are included using the Snippets extension. Instead, you can use the macros plugin for defining snippets.
To this end, add the snippet location using the include_dir
parameter to the plugin's configuration in mkdocs.yml
, for example:
plugins:
- search
- macros:
include_dir: snippets
In your Markdown file, you call the snippets like
{% include 'snip.md' %}
This example illustrates the behavior:
=== "snippets/snip.md"
_Code_
```markdown
Here goes the variable: {{ page.meta.variables.number }}
```
=== "docs/page1.md"
_Code_
```markdown
---
variables:
number: 500
---
{% include 'snip.md' %}
```
_Result_
Here goes the variable: 500
=== "docs/page2.md"
_Code_
```markdown
---
variables:
number: 1000
---
{% include 'snip.md' %}
```
_Result_
Here goes the variable: 1000
Customization
Custom macros
The macros plugin allows to define custom macros, which can then be used from Markdown files. See the official documentation for more information how to define custom macros.