如何在父模板django中访问上下文变量

时间:2017-07-12 23:41:42

标签: python django django-templates

我的主base.html中有_header_main.html和标题为index.html的文件,我扩展base.html并包含_header_main.html但我传入index.html的变量1}}在父模板中不可见

base.html文件:

<html>
    <head>
        <title>{% block title %}{% endblock %}</title>
        <!-- styles -->
        ...
    </head>
    <body>
        {% block _header_main %}{% endblock %}
        {% block _header_mobile %}{% endblock %}
        <div class="wrapper">
        <!-- header -->
        {% block header_main %}{% endblock %}
        {% block header_mobile %}{% endblock %}

        <div class="after_header"></div>
    <!-- end header -->
    {% block content %}{% endblock %}
        <footer class="footer">
            ...
        </footer>
    </div>
    </body>
</html>

_header_main.html:

<header class="header">
    <ul>
    {% for i in servers %}
        <li>{{ i.title }}</li>
    {% endfor %}
    </ul>
</header>

的index.html:

{% extends "base.html" %}
{% load static %}
{% block title %}Title{% endblock %}
{% block header_main %}
    {% include "_header_main.html" %}
{% endblock %}
{% block content %}
    Some content...
{% endblock %}
<scripts>
...
</scripts>

我如何在模板中访问变量items

修改。我在views.py中的功能

def index(request):
    servers = Server.objects.all().order_by('ranking')
    basket_count, total_price = basket_calculate(request)
    server_arr = [i.title for i in servers]
    servers_string = ', '.join(server_arr)
    return render(request, 'index.html', {'servers':servers, 'temp_year' : datetime.now().year,
                                          'basket_count':basket_count, 'total_price':total_price,
                                          'servers_string':servers_string })

1 个答案:

答案 0 :(得分:0)

我的items变量未在模板中显示的原因是因为我添加了<script>标记js而没有阻止,因此我的脚本不起作用。我将我的脚本添加到{% block script %},一切正常!