简体   繁体   中英

How to access context variables in parents template django

I have base.html and file with header _header_main.html in my main template index.html i extends base.html and include _header_main.html but variables that i pass into index.html not visible in parent template

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>

How i can access to variables items in my template?

Edit. My function in 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 })

The reason why my items variable don't show in templates, is because i add <script> tag with js without block, so my scripts didn't work. I add my scripts to {% block script %} and all works fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM