Template Inheritance in Flask
Key Concepts
- Base Template
- Child Template
- Block Sections
1. Base Template
The base template is a foundational HTML file that contains the common structure and elements shared across multiple pages. It serves as a blueprint for other templates.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> <header> <h1>My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html>
2. Child Template
A child template inherits from the base template and extends it by overriding specific sections. This allows for customization without duplicating common elements.
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <h2>Welcome to the Home Page</h2> <p>This is the content specific to the home page.</p> {% endblock %}
3. Block Sections
Block sections are placeholders defined in the base template that can be overridden by child templates. They allow for dynamic content insertion in predefined areas.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> <header> <h1>My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html>
By using template inheritance, you can create a consistent layout across your website while allowing for page-specific content. This approach enhances maintainability and reduces redundancy.
© 2024 Ahmed Baheeg Khorshid. All rights reserved.