0
0
Flaskframework~5 mins

Include for reusable fragments in Flask

Choose your learning style9 modes available
Introduction

Including reusable fragments helps you avoid repeating the same code in multiple places. It makes your web pages easier to build and maintain.

You want to reuse a header or footer on many pages.
You have a navigation menu that appears on all pages.
You want to keep your HTML organized by splitting it into smaller parts.
You need to update a common section and want changes to apply everywhere automatically.
Syntax
Flask
{% include 'filename.html' %}
Use the {% include %} tag inside your Jinja2 templates.
The filename should be a path relative to your templates folder.
Examples
This inserts the content of header.html here.
Flask
{% include 'header.html' %}
This adds the footer section from footer.html.
Flask
{% include 'footer.html' %}
You can include files inside subfolders like nav/menu.html.
Flask
{% include 'nav/menu.html' %}
Sample Program

This example shows a base template that includes a header and footer from separate files. The header has navigation links, and the footer shows a copyright notice. This way, you can reuse the header and footer on many pages.

Flask
{# base.html #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Site</title>
</head>
<body>
    {% include 'header.html' %}
    <main>
        <h1>Welcome to my site</h1>
        <p>This is the main content.</p>
    </main>
    {% include 'footer.html' %}
</body>
</html>

{# header.html #}
<header>
    <nav>
        <a href="/">Home</a> |
        <a href="/about">About</a>
    </nav>
</header>

{# footer.html #}
<footer>
    <p>&copy; 2024 My Site</p>
</footer>
OutputSuccess
Important Notes

If the included file does not exist, Flask will raise an error.

You can pass variables to included templates if needed.

Summary

Use {% include %} to insert reusable HTML parts into your templates.

This helps keep your code DRY (Don't Repeat Yourself).

It makes updating common sections easy and fast.