0
0
Flaskframework~30 mins

Macros for reusable components in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Macros for reusable components in Flask templates
📖 Scenario: You are building a website with Flask. You want to reuse a button design on many pages without repeating the HTML code.
🎯 Goal: Create a Jinja2 macro for a reusable button component. Use this macro in a template to show two buttons with different labels and links.
📋 What You'll Learn
Create a macro named button that takes label and url as parameters
Use the macro to render two buttons with different labels and URLs
Use semantic HTML and accessible attributes for the buttons
Keep the macro in a separate file and import it in the main template
💡 Why This Matters
🌍 Real World
Web developers often reuse UI components like buttons, forms, and cards across many pages. Macros help keep templates clean and consistent.
💼 Career
Knowing how to create and use macros in Flask templates is a valuable skill for backend web developers working with Python and Jinja2 templating.
Progress0 / 4 steps
1
Create the macro file with a button macro
Create a file named macros.html. Inside it, define a macro called button that takes label and url as parameters. The macro should output a <a> tag with href set to url, class btn, and the link text as label.
Flask
Need a hint?

Use {% macro button(label, url) %} to start and {% endmacro %} to end the macro.

Inside, create an <a> tag with href and class.

2
Import the macro file in the main template
In your main template file named index.html, import the macro file macros.html using {% import 'macros.html' as macros %} at the top.
Flask
Need a hint?

Use {% import 'macros.html' as macros %} at the top of index.html to access the macro.

3
Use the macro to create two buttons
In index.html, use the macro macros.button to create two buttons: one with label 'Home' and URL '/', and another with label 'Contact' and URL '/contact'. Place each button inside a <div>.
Flask
Need a hint?

Call the macro with {{ macros.button('Home', '/') }} and {{ macros.button('Contact', '/contact') }} inside <div> tags.

4
Add CSS class for button styling
Add a CSS style block in index.html inside <style> tags. Define the .btn class with padding 0.5rem 1rem, background color #007BFF, text color white, border radius 0.25rem, and remove text underline.
Flask
Need a hint?

Inside <style>, define the .btn class with the given styles for padding, background color, text color, border radius, and no underline.