replace block within {{ super() }}

本秂侑毒 提交于 2020-06-27 08:32:34

问题


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:


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


来源:https://stackoverflow.com/questions/21267620/replace-block-within-super

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!