In modern frontend component architecture (like React components), UI elements are broken down into parameterized, reusable functions. Jinja2 provides the exact same capability for server-rendered Python web applications through Macros.
A macro is analogous to a Python function: it takes arguments (with optional default values) and returns a rendered block of HTML.
Import macros into your pages just like importing Python functions:
You can also import specific macros directly into the local namespace:
One of the most valuable uses of macros is standardizing form input rendering, including error states and labels:
varargs and kwargsJust like Python functions with *args and **kwargs, Jinja2 macros support arbitrary positional and keyword parameters via the special varargs and kwargs variables:
macros/forms.html giving it an alias forms?type='text')?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Template Inheritance & Layout Composition | Flask-WTF Setup & CSRF Token Protection |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.