0
0
Flaskframework~30 mins

Template inheritance with extends in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Template inheritance with extends in Flask
📖 Scenario: You are building a simple website using Flask. You want to create a consistent look for all pages by using a base HTML template. Then, you will create a child template that inherits from the base template and fills in the unique content for the homepage.
🎯 Goal: Build two HTML templates: a base template called base.html with a header and footer, and a child template called home.html that extends base.html and adds a welcome message in the content area.
📋 What You'll Learn
Create a base template base.html with a block content placeholder
Create a child template home.html that uses {% extends 'base.html' %}
Override the content block in home.html with a welcome message
Use semantic HTML tags for header, main content, and footer
💡 Why This Matters
🌍 Real World
Template inheritance helps keep your website consistent and easy to maintain by reusing common layout code.
💼 Career
Understanding template inheritance is essential for web developers working with Flask or other template-based frameworks to build scalable web apps.
Progress0 / 4 steps
1
Create the base template base.html
Create a file called base.html with a basic HTML5 structure. Inside the <body>, add a <header> with the text "My Website Header" and a <footer> with the text "My Website Footer". Between them, add a Jinja2 block named content using {% block content %}{% endblock %}.
Flask
Need a hint?

Use {% block content %}{% endblock %} inside the body between header and footer.

2
Create the child template home.html that extends base.html
Create a file called home.html. At the top, write {% extends 'base.html' %} to inherit from the base template. Then, open a content block using {% block content %}.
Flask
Need a hint?

Start your file with {% extends 'base.html' %} and then open the content block.

3
Add a welcome message inside the content block
Inside the content block in home.html, add a <main> tag with a <h1> that says "Welcome to the Homepage!". Then close the content block with {% endblock %}.
Flask
Need a hint?

Wrap the welcome message in a <main> tag and close the block with {% endblock %}.

4
Use the templates in a Flask route
In your Flask app file, import Flask and render_template. Create an app instance. Define a route for / that returns render_template('home.html'). Make sure to include the if __name__ == '__main__': block to run the app.
Flask
Need a hint?

Use @app.route('/') and a function that returns render_template('home.html').