0
0
Flaskframework~30 mins

Include for reusable fragments in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Include for Reusable Fragments in Flask Templates
📖 Scenario: You are building a simple website with Flask. You want to reuse the same navigation bar on multiple pages without copying the code each time.
🎯 Goal: Create a Flask project that uses template include to reuse a navigation bar fragment in two different HTML pages.
📋 What You'll Learn
Create a base HTML file with a navigation bar fragment in a separate file
Use Flask's render_template to render pages
Use Jinja2 {% include %} to insert the navigation bar fragment into pages
Create two pages that both include the navigation bar fragment
💡 Why This Matters
🌍 Real World
Web developers often reuse parts of web pages like headers, footers, or navigation bars to keep code clean and consistent across many pages.
💼 Career
Knowing how to use template includes is essential for building maintainable web applications with Flask or other template-based frameworks.
Progress0 / 4 steps
1
Create the navigation bar fragment file
Create a file called nav.html inside the templates folder. Add a simple navigation bar with an unordered list containing links: Home, About, Contact.
Flask
Need a hint?

Use HTML <nav> and <ul> tags. Put three <li> items with links inside.

2
Create the home page template including the nav fragment
Create a file called home.html inside the templates folder. Use Jinja2 {% include 'nav.html' %} to insert the navigation bar at the top. Below it, add a heading <h1>Welcome to the Home Page</h1>.
Flask
Need a hint?

Use {% include 'nav.html' %} exactly to insert the nav bar. Then add the heading below.

3
Create the about page template including the nav fragment
Create a file called about.html inside the templates folder. Use Jinja2 {% include 'nav.html' %} to insert the navigation bar at the top. Below it, add a heading <h1>About Us</h1>.
Flask
Need a hint?

Use the same include syntax as before. Change the heading text to 'About Us'.

4
Create the Flask app to render the pages
Create a file called app.py. Import Flask and render_template. Create a Flask app instance called app. Add two routes: / rendering home.html and /about rendering about.html. Finally, add the if __name__ == '__main__' block to run the app with debug mode on.
Flask
Need a hint?

Follow Flask basics: import, create app, define routes with decorators, return render_template calls, and run the app.