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.
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.
{% extends 'base.html' %}
{% block content %}
<!-- page specific content here -->
{% endblock %}extends tag tells Flask which template to use as the base layout.block tags define sections that child templates can fill with their own content.{% extends 'layout.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
<p>Welcome to the home page!</p>
{% endblock %}{% extends 'base.html' %}
{% block sidebar %}
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul>
{% endblock %}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.
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 %}
block tags where you want child templates to insert content.{% extends %} to inherit from a base template.{% block %} tags.{% extends %} in Flask templates?{% extends %}{% extends %}.base.html?{% extends 'filename' %}.{% include %} inserts content but does not inherit; {% import %} is for macros; {% block %} defines sections, not inheritance.base.html with a block named content and a child template that extends it and overrides content, what will be displayed when rendering the child template?content block -> Option B{% extends 'base.html' %}
{% block content %}
Hello World
{% endblock %}, not with HTML-like closing tags.p tags are allowed inside blocks.{% endblock %} instead of -> Option Abase.html with two blocks: header and content. You want a child template to reuse the base layout but only change the content block, keeping the base header as is. Which is the correct approach?header block in the child; only override content.base.html and define only the content block; omit the header block -> Option DPass the test and this pattern moves unknown