Django テンプレートの継承でblockの中身のoverrideとinsert
Django テンプレートを使っているとblockがとても便利で使うことが多い。
と言うより使わざるを得ないので必ず使う。
基本、親テンプレートの中で
で使うことが出来る。{% block block_name %}{% endblock %}
を指定して、親テンプレートを
extends
した子テンプレートで
{% block block_name %}...子の中身...{% endblock %}
ところで、このようにすると、親テンプレートが
になっている時は、親の中身は全部上書き(override)される。{% block block_name %}...親の中身...{% endblock %}
もし、親の中身を残したまま、この中身を追加(insert)したい場合は、
を利用する。{{ block.super }}
https://docs.djangoproject.com/en/3.0/ref/templates/language/#template-inheritance
If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }} will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.
つまり、下記のように子テンプレートで記述すると「親の中身」の下に「子の中身」を追加することが出来る。
{% block block_name %}
{{ block.super }}
...子の中身...
{% endblock %}
ディスカッション
コメント一覧
まだ、コメントがありません