我有一个名为base.html的模板。顾名思义,它是页眉和页脚所在的地方。在这两个元素之间是一个{% block content %},子模板可以扩展该模板并在块内容中添加内容。
但是,在标题中,我希望显示用户名。例如,当我将这个模板扩展到子模板时,{{ user.username }}但是Django似乎无法识别这一点。有办法将对象传递给扩展模板吗?这样就可以显示登录的用户名了吗?
这是我试图做的一个粗略的例子。即使在用户登录时,user.username也不会显示。
base.html
<header>
<h1>Hello, {{ user.username }}</h1>
</header>
{% block content %}{% endblock %}
<footer>
///Some content
</footer>child.html
{% extends 'base.html' %}
{% block content %}
//Some content
{% endblock %}views.py for child.html
ChildView(TemplateView):
template_name = 'child.html'发布于 2018-07-30 02:24:17
这是因为子模板中的blocks中的内容是覆盖的。
base.html
{% block my_block %}
This content is overriden by child templates
{% endblock my_block %}child.html
{% extends 'base.html' %}
{% block my_block %}
This content is shown
{% endblock my_block %}如果希望在所有模板中显示某些内容,则不应将其放入块内容中,而应直接放在基本模板中。
base.html
{{ user.username }}
{% block my_block %}
This content is overriden by child templates
{% endblock my_block %}所以,这一切都取决于你的页面布局是如何完成的。如果标头始终相同,则不应使用块标记。
如果几乎相同,但细节上有变化,则使用块来更改详细信息:
报头
<h1>This doesn't change ever
{% block this_changes %}
the child themplate will provide the content
{% endblock this_changes %}</h1>
<b>User: {{ user.username }}</b>https://stackoverflow.com/questions/51585881
复制相似问题