Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 647
golmschenk Avatar asked Jan 21 '14 19:01

golmschenk


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 %}
like image 131
Alvaro Fuentes Avatar answered Nov 15 '22 12:11

Alvaro Fuentes


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 %}
like image 28
Milovan Tomašević Avatar answered Nov 15 '22 12:11

Milovan Tomašević