How does the "extends" and "block endblock" commands of Jinja2 work?

Asked

Viewed 744 times

1

I’m using Jinja2 to create templates for my application. However, I was confused about two of its features.

The features are:

The command extends:

{% extends 'pagina-exemplo.html' %}

and the command block:

{% block content %}

{% endblock  %}

I don’t really know how they work, or how the template inheritance mechanism works with respect to these two commands.

Question

  • How comados work extends and block endblock jinja2?

1 answer

3


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 %}
        &copy; 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.