Template Blocks
A block is a named placeholder region that child templates can override.
Defining blocks
<!-- base.html -->
{% block content %}{% endblock %}<!-- base.html -->
{% block content %}{% endblock %}Overriding blocks
<!-- page.html -->
{% extends "base.html" %}
{% block content %}
<h1>Page content</h1>
{% endblock %}<!-- page.html -->
{% extends "base.html" %}
{% block content %}
<h1>Page content</h1>
{% endblock %}Using multiple blocks
Base templates often have blocks like:
titletitlecontentcontentscriptsscripts
{% block scripts %}{% endblock %}{% block scripts %}{% endblock %}Child template:
{% block scripts %}
<script src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}{% block scripts %}
<script src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}Extending a block (super)
If you want to add to a parent block rather than replace it:
{% block scripts %}
{{ super() }}
<script src="{{ url_for('static', filename='extra.js') }}"></script>
{% endblock %}{% block scripts %}
{{ super() }}
<script src="{{ url_for('static', filename='extra.js') }}"></script>
{% endblock %}Thatβs useful for base scripts shared across pages.
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
