首页 文章

将变量传递到扩展模板?

提问于
浏览
0

我有一个名为 base.html 的模板 . 顾名思义,它就是页眉和页脚所在的位置 . 在这两个元素之间,是一个 {% block content %} ,其中子模板可以扩展此模板并在块内容中添加内容 .

但是,在内部 Headers 中我希望显示用户的名称 . 例如, {{ user.username }} 但是Django可以显示't seem to recognize this when I extend this template to a child template. Is there a way I can pass in objects to the extends template? That way the logged in user'的名字吗?

这是我正在尝试做的一个粗略的例子 . 即使用户已登录,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'

2 回答

  • 0

    这是因为子模板中 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 %}
    

    所以,这一切都取决于页面布局是如何完成的 . 如果 Headers 始终相同,则不应使用块标记 .

    如果它几乎相同,但细节发生变化,请使用块来更改细节:

    header

    <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>
    
  • 0

    在您的子模板中,将其添加到顶部

    {% extends 'base.html' %}
    

    这将允许您“继承”上下文变量 .

    或者,如果您只想将 user 数据传递给模板,则可以在 base.html 中执行以下操作:

    {% include 'header.html' with my_user=user %}
    

    This回答总结了 extendinclude 功能之间的差异 .


    Edit

    在回复您的评论和更新的问题时,您没有正确访问 user 对象 . 为此,您必须使用 {{ request.user }} . 这是因为there is a context processor that passes the user object to every template .

    顺便说一句,如果您要从视图中明确发送 user ,则可以使用 {{ user }} 来访问用户 . 但是,这显然是非常不必要的 .

相关问题