【问题标题】:How to access context variables in parents template django如何访问父母模板django中的上下文变量
【发布时间】:2017-12-17 13:27:57
【问题描述】:

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

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 })

【问题讨论】:

  • 请展示你的观点。

标签: python django django-templates


【解决方案1】:

我的items 变量没有显示在模板中的原因是因为我添加了&lt;script&gt; 标记和js 没有阻止,所以我的脚本没有工作。我将我的脚本添加到 {% block script %} 并且一切正常!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2019-11-10
    • 2019-12-05
    • 2011-08-29
    相关资源
    最近更新 更多