这是我的其他html页面扩展的基本html页面(称为base.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Django Bookmarks | {% block title %}{% endblock %}</title>
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
</head>
<body>
{% block header %}
<p> signed in! </p>
{% endblock %}
{% block content %}{% endblock %}
</body>
</html>
现在,这是我的主页。
{% extends "base.html" %}
{% block title %} Title {% endblock %}
{% if user.username %}
{% else %}
{% block header %}{% endblock %}
{% endif %}
{% block content %}
{% if user.username %}
<p>Welcome {{ user.username }}.</p>
{% else %}
<p>Not Signed in</p>
{% endif %}
{% endblock %}
如你所见,我想要我的
{% block header %}{% endblock %}
如果没有用户登录,则为空,但如果有用户登录,我想要
{% block header %}
从base.html继承。但是,即使用户已登录,它也不会从base.html继承。用户登录时不会显示标题块。任何想法为什么?
答案 0 :(得分:5)
使用block.super
:
{% block header %}
{% if user.username %}
{{ block.super }}
{% else %}
{# empty #}
{% endif %}
{% endblock %}
根据Django template documentation:
如果您需要从父模板获取块的内容,
{{ block.super }}
变量可以解决问题。如果,这很有用 您想要添加到父块的内容而不是 完全压倒它。 .....