Labs ICT
โญ Pro Login

Template Inheritance

Building reusable page layouts.

Template Inheritance

Template inheritance is a powerful feature that keeps your code DRY (Don't Repeat Yourself). Instead of copying the same header and footer into every HTML file, you create a base template with the common elements, then child templates that only override what's different.

Create a base.html file in your templates folder. This will be your parent template:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
    </nav>
    
    {% block content %}{% endblock %}
    
    <footer>
        <p>ยฉ 2026 My Flask App</p>
    </footer>
</body>
</html>

Now, create child templates that extend this base. Use {% extends "base.html" %} at the top, then define blocks to override:

{% extends "base.html" %}

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

{% block content %}
    <h1>Welcome to my website!</h1>
    <p>This is the home page content.</p>
{% endblock %}

See how clean that is? You don't repeat the HTML structure, head, nav, or footer. Just the unique content for each page. The {% block %} tags define placeholders that child templates can fill in.

You can have multiple blocks. Maybe you want one for the main content and another for sidebar content:

<div class="main">
    {% block content %}{% endblock %}
</div>

<div class="sidebar">
    {% block sidebar %}{% endblock %}
</div>

Sometimes you want to keep the parent block's content and add to it. Use {{ super() }} to include the parent's content:

{% block content %}
    {{ super() }}
    <p>This is additional content I'm adding.</p>
{% endblock %}

This inheritance approach means if you need to change the navigation, you just edit base.html and all pages update automatically. Much easier than editing every single template file.

Try it Yourself ->

๐Ÿงช Quick Quiz

How does template inheritance work?