Macros
The astute reader will have noticed that, in the previous example, we had some repeated code. Repeating code is the enemy of any developer, and thankfully, Jinja2 has a way to help! A macro is like a function in a regular programming language; it's a way to define a reusable idiom. A macro is defined inside a {% macro ... %} ... {% endmacro %} block and has a name, and can take zero or more arguments. Code within a macro does not inherit the namespace of the block calling the macro, so all arguments must be explicitly passed in. Macros are called within curly brace blocks by name, and with zero or more arguments passed in via parentheses. Let's create a simple macro named comma to take the place of our repeating code:
{% macro comma(loop) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access