0
0
Flaskframework~5 mins

Template inheritance with extends in Flask

Choose your learning style9 modes available
Introduction

Template inheritance helps you reuse common parts of web pages easily. It saves time by letting you build a base layout and add specific content on top.

You want all pages on your website to share the same header and footer.
You need to create multiple pages that look similar but have different main content.
You want to keep your HTML code clean and avoid repeating the same code in every file.
You are building a website with many pages and want to update the design quickly in one place.
Syntax
Flask
{% extends 'base.html' %}

{% block content %}
  <!-- page specific content here -->
{% endblock %}
The extends tag tells Flask which template to use as the base layout.
The block tags define sections that child templates can fill with their own content.
Examples
This example shows a child template that sets a page title and main content inside blocks.
Flask
{% extends 'layout.html' %}

{% block title %}Home Page{% endblock %}

{% block content %}
  <p>Welcome to the home page!</p>
{% endblock %}
This example overrides a sidebar block to add a custom menu.
Flask
{% extends 'base.html' %}

{% block sidebar %}
  <ul>
    <li>Link 1</li>
    <li>Link 2</li>
  </ul>
{% endblock %}
Sample Program

This example shows a base template with header, footer, and content blocks. The home.html file extends base.html and fills in the title and content blocks with page-specific content.

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>{% block title %}My Website{% endblock %}</title>
</head>
<body>
  <header>
    <h1>My Website Header</h1>
  </header>

  <main>
    {% block content %}
    <p>Default content.</p>
    {% endblock %}
  </main>

  <footer>
    <p>My Website Footer</p>
  </footer>
</body>
</html>

home.html:
{% extends 'base.html' %}

{% block title %}Home Page{% endblock %}

{% block content %}
  <p>Welcome to the home page!</p>
{% endblock %}
OutputSuccess
Important Notes
Always make sure the base template has block tags where you want child templates to insert content.
You can override as many blocks as you want in the child template.
If a block is not overridden, the base template's content for that block will show.
Summary
Template inheritance lets you create a base layout and reuse it across pages.
Use {% extends %} to inherit from a base template.
Fill in or override sections using {% block %} tags.