MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Jinja2 Macros & Reusable UI Components0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
3.1Jinja2 Syntax, Variables & Custom Filters3.2Control Structures, Loops & Conditionals3.3Template Inheritance & Layout Composition3.4Jinja2 Macros & Reusable UI Components
HomeTutorialsFlaskJinja2 Macros & Reusable UI Components
Flask-WTF Setup & CSRF Token Protection

Jinja2 Macros & Reusable UI Components

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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.


1. What is a Jinja2 Macro?

A macro is analogous to a Python function: it takes arguments (with optional default values) and returns a rendered block of HTML.

Defining a Basic Macro:

1<!-- templates/macros/ui.html -->
2{% macro render_badge(text, variant='primary') %}
3 {% if variant == 'success' %}
4 <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-emerald-100 text-emerald-800">
5 {{ text }}
6 </span>
7 {% elif variant == 'danger' %}
8 <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-red-100 text-red-800">
9 {{ text }}
10 </span>
11 {% else %}
12 <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-indigo-100 text-indigo-800">
13 {{ text }}
14 </span>
15 {% endif %}
16{% endmacro %}

2. Importing and Using Macros in Templates

Import macros into your pages just like importing Python functions:

1<!-- templates/profile.html -->
2{% extends "base.html" %}
3{% import "macros/ui.html" as ui %}
4 
5{% block content %}
6<div class="user-card">
7 <h2>{{ user.name }}</h2>
8 <div class="status-tags">
9 {{ ui.render_badge("Active Student", variant="success") }}
10 {{ ui.render_badge("Python Certified", variant="primary") }}
11 </div>
12</div>
13{% endblock %}

You can also import specific macros directly into the local namespace:

1{% from "macros/ui.html" import render_badge %}
2{{ render_badge("Pro Member") }}

3. Building an Enterprise Form Field Macro

One of the most valuable uses of macros is standardizing form input rendering, including error states and labels:

1<!-- templates/macros/forms.html -->
2{% macro render_input(name, label, type='text', value='', placeholder='', error=None, required=False) %}
3<div class="form-group mb-4">
4 <label for="{{ name }}" class="block text-sm font-semibold text-gray-700 mb-1">
5 {{ label }} {% if required %}<span class="text-red-500">*</span>{% endif %}
6 </label>
7
8 <input
9 type="{{ type }}"
10 id="{{ name }}"
11 name="{{ name }}"
12 value="{{ value }}"
13 placeholder="{{ placeholder }}"
14 class="w-full px-4 py-2 rounded-lg border {% if error %}border-red-500 bg-red-50 text-red-900{% else %}border-gray-300 focus:border-indigo-500{% endif %} focus:outline-none focus:ring-2 focus:ring-indigo-200 transition"
15 {% if required %}required{% endif %}
16 >
17
18 {% if error %}
19 <p class="mt-1 text-xs text-red-600 font-medium">{{ error }}</p>
20 {% endif %}
21</div>
22{% endmacro %}

Usage in Checkout Template:

1{% from "macros/forms.html" import render_input %}
2 
3<form method="POST" action="/checkout">
4 {{ render_input('full_name', 'Full Legal Name', placeholder='Sumit Verma', required=True) }}
5 {{ render_input('email', 'Email Address', type='email', placeholder='sumit@example.com', required=True) }}
6 {{ render_input('phone', 'Phone Number', type='tel', placeholder='+91 9876543210') }}
7
8 <button type="submit" class="btn btn-primary">Proceed to Payment</button>
9</form>

4. Variadic Arguments with varargs and kwargs

Just like Python functions with *args and **kwargs, Jinja2 macros support arbitrary positional and keyword parameters via the special varargs and kwargs variables:

1{% macro render_button(label) %}
2 <button class="btn" {% for key, val in kwargs.items() %}{{ key }}="{{ val }}" {% endfor %}>
3 {{ label }}
4 </button>
5{% endmacro %}
6 
7<!-- Call with dynamic HTML data-attributes -->
8{{ render_button('Delete Item', id='btn-del', data_modal='confirm-modal') }}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What Jinja2 statement defines a reusable parameterized UI block?
Question 2
How do you import a macro file macros/forms.html giving it an alias forms?
Question 3
How do macros help improve web application security and accessibility?
Question 4
What special variable inside a macro holds arbitrary keyword arguments passed during invocation?
Question 5
Can default values be specified for macro arguments (e.g. type='text')?
Next Lesson

Flask-WTF Setup & CSRF Token Protection

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Template Inheritance & Layout CompositionFlask-WTF Setup & CSRF Token Protection

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext