0
0
Flaskframework~5 mins

Block definitions and overriding in Flask

Choose your learning style9 modes available
Introduction

Blocks let you create parts of a webpage that can be changed later. This helps you reuse layouts and change only what you want.

You want a main page layout but different pages have different content.
You want to keep a header and footer the same on all pages but change the middle part.
You want to create a base template and let other templates add or change sections.
You want to avoid repeating the same HTML code on every page.
Syntax
Flask
{% block block_name %}
  Default content here
{% endblock %}

<!-- To override in child template -->
{% extends 'base.html' %}
{% block block_name %}
  New content here
{% endblock %}

Use {% block %} to define a replaceable section in your base template.

Use {% extends %} in child templates to inherit and override blocks.

Examples
Defines a block named title with default text 'My Site'.
Flask
{% block title %}My Site{% endblock %}
Overrides the title block in the base template to show 'Home Page'.
Flask
{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
Defines a content block with a welcome message.
Flask
{% block content %}
  <p>Welcome to my website!</p>
{% endblock %}
Sample Program

This example shows a base template with blocks for title and content. The home.html template extends the base and overrides these blocks to show a custom title and 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 %}Default Title{% endblock %}</title>
</head>
<body>
  <header>
    <h1>My Website</h1>
  </header>
  <main>
    {% block content %}
    <p>This is the default content.</p>
    {% endblock %}
  </main>
  <footer>
    <p>Ā© 2024 My Website</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

Blocks help keep your templates clean and avoid repeating code.

If a block is not overridden, the default content inside the block is shown.

Always use {% extends %} at the very top of your child templates.

Summary

Blocks define parts of a template that can be changed in child templates.

Use {% block %} and {% endblock %} to create blocks.

Use {% extends %} to inherit and override blocks in other templates.