Bird
Raised Fist0
Flaskframework~10 mins

Macros for reusable components in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Macros for reusable components
Define macro in template
↓
Use macro in same or other template
↓
Render template
↓
Macro expands to HTML
↓
Final HTML sent to browser
Macros are like little helpers in templates. You define them once, then use them many times to create repeated HTML parts easily.
Execution Sample
Flask
{% macro button(text, url) %}
  <a href="{{ url }}" class="btn">{{ text }}</a>
{% endmacro %}

{{ button('Home', '/') }}
Defines a button macro and uses it to create a link styled as a button.
Execution Table
StepActionMacro CalledParametersOutput HTML
1Define macro 'button'No--
2Call macro 'button'Yestext='Home', url='/'<a href="/" class="btn">Home</a>
3Insert macro output into templateNo-<a href="/" class="btn">Home</a>
4Render final HTMLNo-<a href="/" class="btn">Home</a>
💡 All macro calls expanded and template fully rendered
Variable Tracker
VariableStartAfter Macro CallFinal
textundefinedHomeHome
urlundefined//
Key Moments - 3 Insights
Why does the macro need parameters like 'text' and 'url'?
Parameters let the macro create different buttons each time. See execution_table step 2 where 'text' and 'url' change the output.
Can I use a macro before defining it in the template?
No, macros must be defined before use. Step 1 shows macro definition happens first.
Does the macro output replace the macro call in the final HTML?
Yes, as shown in step 3 and 4, the macro call is replaced by the generated HTML.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output HTML after the macro call at step 2?
A<button>Home</button>
B<a href="#" class="btn">Home</a>
C<a href="/" class="btn">Home</a>
D<a href="/home" class="btn">Home</a>
💡 Hint
Check the 'Output HTML' column at step 2 in the execution_table
At which step is the macro 'button' defined?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in the execution_table for macro definition
If you change the parameter 'text' to 'About', what will be the output HTML at step 2?
A<a href="/" class="btn">About</a>
B<a href="/" class="btn">Home</a>
C<a href="/about" class="btn">About</a>
D<button>About</button>
💡 Hint
Refer to variable_tracker for 'text' value and execution_table step 2 output pattern
Concept Snapshot
Macros in Flask templates:
- Define with {% macro name(params) %}...{% endmacro %}
- Call with {{ name(args) }}
- Reusable HTML snippets
- Parameters customize output
- Expands to HTML during rendering
Full Transcript
In Flask templates, macros let you create reusable HTML parts. First, you define a macro with parameters. Then you call it with specific values. When rendering, the macro call is replaced by the HTML it generates using those values. This helps avoid repeating code and keeps templates clean. For example, a button macro can be defined once and used many times with different text and links. The execution table shows defining the macro, calling it with parameters, and rendering the final HTML. Variables like 'text' and 'url' hold the values passed to the macro. Remember, macros must be defined before use, and their output replaces the call in the final page.

Practice

(1/5)
1. What is the main purpose of using {% macro %} in Flask templates?
easy
A. To create reusable blocks of HTML code
B. To define Python functions inside templates
C. To import external CSS files
D. To handle form submissions

Solution

  1. Step 1: Understand what macros do in Flask templates

    Macros are used to write reusable HTML blocks that can be called multiple times to avoid repetition.
  2. Step 2: Compare options with macro purpose

    Only To create reusable blocks of HTML code correctly describes macros as reusable HTML blocks. Other options describe unrelated tasks.
  3. Final Answer:

    To create reusable blocks of HTML code -> Option A
  4. Quick Check:

    Macros = reusable HTML blocks [OK]
Hint: Macros create reusable HTML snippets in templates [OK]
Common Mistakes:
  • Thinking macros define Python functions
  • Confusing macros with CSS imports
  • Assuming macros handle form data
2. Which of the following is the correct syntax to define a macro named button that takes a parameter label?
easy
A. {% define button(label) %} {{ label }} {% enddefine %}
B. {% macro button(label) %} {{ label }} {% endmacro %}
C. {{ macro button(label) }} {{ label }} {{ endmacro }}
D. <% macro button(label) %> {{ label }} <% endmacro %>

Solution

  1. Step 1: Recall correct macro syntax in Flask Jinja templates

    Macros are defined with {% macro name(params) %} ... {% endmacro %} tags.
  2. Step 2: Check each option's syntax

    {% macro button(label) %} {{ label }} {% endmacro %} uses correct {% %} tags and endmacro. Others use wrong delimiters or keywords.
  3. Final Answer:

    {% macro button(label) %} <button>{{ label }}</button> {% endmacro %} -> Option B
  4. Quick Check:

    Macro syntax = {% macro %} ... {% endmacro %} [OK]
Hint: Use {% macro %} and {% endmacro %} to define macros [OK]
Common Mistakes:
  • Using {{ }} instead of {% %} for macro definition
  • Using incorrect keywords like define or <% %>
  • Forgetting the endmacro tag
3. Given the macro defined in macros.html as:
{% raw %}{% macro greet(name) %}Hello, {{ name }}!{% endmacro %}{% endraw %}

And imported in index.html with:
{% raw %}{% import 'macros.html' as m %}{% endraw %}

What will be the output of {{ m.greet('Alice') }} in index.html?
medium
A. Error: macro not found
B. {{ m.greet('Alice') }}
C. greet('Alice')
D. Hello, Alice!

Solution

  1. Step 1: Understand macro import and usage

    The macro greet(name) returns 'Hello, {{ name }}!'. Importing as m allows calling m.greet('Alice').
  2. Step 2: Evaluate the macro call output

    Calling m.greet('Alice') replaces {{ name }} with 'Alice', so output is 'Hello, Alice!'.
  3. Final Answer:

    Hello, Alice! -> Option D
  4. Quick Check:

    Macro call with parameter = rendered string [OK]
Hint: Imported macros called with alias render output [OK]
Common Mistakes:
  • Expecting literal macro call text instead of rendered output
  • Forgetting to import macros before use
  • Confusing macro call syntax with variable output
4. What is wrong with this macro usage in a Flask template?
{% raw %}{% macro card(title) %}
{{ title }}
{% endmacro %}{% endraw %}
{{ card() }}
medium
A. The macro is not properly closed with {% endmacro %}
B. Macros cannot return HTML elements
C. The macro is called without the required parameter
D. The macro name is invalid

Solution

  1. Step 1: Check macro definition and parameters

    The macro card requires one parameter: title.
  2. Step 2: Check macro call

    The call {{ card() }} provides no argument, causing an error due to missing parameter.
  3. Final Answer:

    The macro is called without the required parameter -> Option C
  4. Quick Check:

    Missing macro argument = error [OK]
Hint: Always pass required parameters when calling macros [OK]
Common Mistakes:
  • Calling macros without required arguments
  • Thinking macros must return plain text only
  • Missing endmacro tag (not the case here)
5. You want to create a reusable navigation bar macro that highlights the current page. Which approach correctly uses macros and parameters to achieve this?
hard
A. {% raw %}{% macro navbar(current) %}{% endmacro %}{% endraw %} Then call with {{ navbar('about') }}
B. {% raw %}{% macro navbar() %}{% endmacro %}{% endraw %} Then call with {{ navbar() }}
C. {% raw %}{% macro navbar(current) %}{% endmacro %}{% endraw %} Then call with {{ navbar('home') }}
D. {% raw %}{% macro navbar(current) %}{% endmacro %}{% endraw %} Then call with {{ navbar('home') }}

Solution

  1. Step 1: Understand the need for dynamic class assignment

    The macro should accept a parameter to know which page is current and add 'active' class accordingly.
  2. Step 2: Analyze each option's approach

    {% raw %}{% macro navbar(current) %}{% endmacro %}{% endraw %} Then call with {{ navbar('about') }} uses a parameter and conditional expression to add 'active' class only to the current page link. Others either hardcode classes or ignore the parameter.
  3. Final Answer:

    Uses parameters and conditional logic to highlight current page -> Option A
  4. Quick Check:

    Dynamic class with parameter = correct navbar macro [OK]
Hint: Use macro parameters with conditionals for dynamic HTML [OK]
Common Mistakes:
  • Hardcoding active class without parameters
  • Ignoring the current page parameter
  • Assigning 'current' class to all links
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard