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?
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 %}