Replace Block Within {{ Super() }}

I have a base template which includes a block for the default <head> content. Within the head block, there's a block for the <title>.

For example, in the base file I would have:

<head>
    {% block head %}
    {% block title %}<title>An App</title>{% endblock title %}
    <script src="somescript.js"></script>
    {% endblock head %}
</head>

In the child template, I would like to include everything that was in the head block from the base (by calling {{ super()) }} and include some additional things, yet at the same time replace the title block within the super call.

Is there a way to do this without just putting a block around the rest of the head content (excluding the title) and just replacing all of that?

1

2 Answers

Don't call super. In your child template you can do:

{% extends "base.html" %}
{% block title %}<title>This is my new TITLE</title>{% endblock %}

Jinja replaces all the blocks in the parent by the ones defined in the child, if you do not provide a new definition it uses the definition in the parent. So it will render as:

<head>

    <title>TITLE</title>
    <script src="somescript.js"></script>

</head>

You call super if you want the default value of the block in the parent:

{% extends "base.html" %}
{% block title %}<title>TITLE</title>{{ super() }}{% endblock %}

And this renders as:

<head>

    <title>TITLE</title><title>An App</title>
    <script src="somescript.js"></script>

</head>

If you want to add more scripts just make a place holder block in your base template:

<head>
    {% block head %}
    {% block title %}<title>An App</title>{% endblock title %}
    <script src="somescript.js"></script>
    {% block moreScripts %}{% endblock moreScripts %}
    {% endblock head %}
</head>

And use it as in :

{% extends "base.html" %}
{% block title %}<title>TITLE</title>{% endblock %}
{% block moreScripts %}
<script src="somescript1.js"></script>
<script src="somescript2.js"></script>
<script src="somescript3.js"></script>
{% endblock moreScripts %}
3

Note:

If the application needs to add its own content to a block that already has some content, then Jinja2’s super() function must be used.

For example, this is how the scripts block would need to be written in the derived template to add a new JavaScript file to the document:

{% block scripts %}
  {{ super() }}
  <script type="text/javascript" src="my-script.js"></script> 
{% endblock %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest