The tags extends
and block
work together and serve to build templates with ideas of inheritance, overlapping and reuse.
In a template you can define numerous tags block
, which can later be overwritten or reused by "child" templates. Children intend to use "parents" templates via the block extends
, what matters the template and now the child will "see" the father’s blocks. The children will fill in the tags block
with the desired content, or even reuse what is already in the parent with the command super
.
Below is a full example taken from the Jinja2 documentation:
Filing cabinet base.html
which will be used as template (parent) for the other children.
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
Filing cabinet child.html
that "extends" the father base.html
, override some block
that desires and also uses portions of the parent code using super()
.
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
Notice the use of the command extends
before starting the blocks. It is important to note that the blocks should be unique in the file, that is, you cannot define multiple blocks of the same name. This limitation exists so that the child knows exactly which portion of the block to fill. Also, if you want to reuse the same block several times in your template, just use the command self.bloco()
where bloco()
is the name of the block you want to reuse.