DEV Community

shravan jain
shravan jain

Posted on • Edited on

Write Less, Reuse More: Template Inheritance in Flask Explained

This turned out to be a pretty cool concept. While working on my site monitoring app, I had around three or four services like uptime checks, DNS lookups, pinging, and a few others. Since I’m not much of a UI designer, I ended up creating separate files for each service, even though they all shared the same layout.

That’s when I discovered Flask’s template inheritance. Instead of repeating the same code over and over, you can create a base layout and reuse it wherever you want. It really helped clean things up and made everything way easier to manage. Here’s how you can set it up.

Inheriting from base to child:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>template-inheritance</title> </head> <body> <header> <nav> <ul> <a href="home">home</a> <a href="about">about</a> <a href="contact">contact</a> </ul> </nav> </header> <main> {% block content %}{% endblock %} </main> <footer> &copy; 2025 My Site </footer> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

Simply put, if you want to use the same template like reusing the same navigation bar across multiple pages, you can just extend the base file. The whole layout gets reused automatically.

And if you want to change something specific on a page, you define blocks in the base file that let you override those sections whenever you need to. For example, if you want to override content inside the tag, you would define a block like this in the base:

 <main> {% block content %}{% endblock %} </main> 
Enter fullscreen mode Exit fullscreen mode

Then, in your child template, you extend the base and override that block:

{% extends "base.html" %} {% block content %} <div class="content"> hello world!! </div> {% endblock %} 
Enter fullscreen mode Exit fullscreen mode

That way, you get the shared layout and can customize parts of the page without repeating your code.

Top comments (0)