Skip to content

Macros for templating

Macros are useful when you want reusable styling, structure, and so on.

Example: Use a macro and YAML file to generate a custom-styled list

This example uses the YAML in _yaml/large-example.yml. Refer to External YAML files for guidance on including YAML files.

Code

Create an HTML file containing your macro:

{% macro prettyList(color, name, sweetness) %}
  <li class="{{ color }}">{{ name }} : {{ sweetness }}</li>
{% endmacro %}

Add some custom CSS:

.green {
  color: green;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow
}

Refer to MkDocs - extra_css for more information on custom CSS with MkDocs.

Import the macro and iterate over the YAML:

{% import "_macros/pretty-list.html" as list %}

<ul>
{% for fruit in fruits %}
{{ list.prettyList(fruit.color, fruit.name, fruit.sweetness) }}
{% endfor %}
</ul>

Refer to the Jinja2 Import documentation for more information about import.

Nunjucks and Jinja2

The Jinja2 documentation is sometimes hard to browse. Nunjucks is a JavaScript port of Jinja2. The documentation contents are similar, but better presented, and occasionally contain more detail. Nunjucks Templating docs.

You can also search for solutions in either templating language if you're looking for examples of how to do something.

Output

  • apple : 4/10
  • orange : 6/10
  • melon : 8/10