0

I written a base html for another html

base.html

        {% for foo in subjectType %}
            <li class="nav-item">
                <a class="nav-link" href="{% url "type" foo.type_name %}">{{ foo.type_name }}</a>
            </li>
        {% endfor %}

and my navbar extends from base.html,but other html extends base.html,Can't display correct navbar.because other cant get "subjectType"

How can I code this?

I use python3.6.5 and django2.0

Senura Dissanayake
  • 654
  • 1
  • 9
  • 29
notyeat
  • 11
  • 5
  • Advice: Put your navbar inside your `base.html`, and all the other html will extend `base.html`, or put the navbar in a separate file, and include it in your `base.html`. and to edit navbar item from your navbar, use {% block name %}{% endblock %}. it's more powerful, and more readable – Lemayzeur Apr 24 '18 at 02:44

2 Answers2

0

You can implement navbar html module using Inclusion tag, then you do not need transfer it for template in view code。

Hayden
  • 449
  • 4
  • 13
0

The main reason is that you are passing context from view in different html.

while extending other html the one you include or extend won't be able to access context which you passed in your template hence you need to override that particular block in template

You can work with templates as below:

base.html

{% block navbar %} base {% endblock %}
{% block body %} base {% endblock %}

Now if you render home.html from view it should be:

home.html

{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block navbar %}
    {% for foo in subjectType %}
    <li class="nav-item">
        <a class="nav-link" href="{% url "type" foo.type_name %}">{{ foo.type_name }}</a>
    </li>
    {% endfor %}
{% endblock %}

So if you pass context using template home.html you need to override navbar if you want to use context

Also you can create another html and include in template as:

navbar.html

{% for foo in subjectType %}
<li class="nav-item">
    <a class="nav-link" href="{% url "type" foo.type_name %}">{{ foo.type_name }}</a>
</li>
{% endfor %}

home.html

{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block navbar %}
    {% include 'navbar.html' %}
{% endblock %}
Gahan
  • 4,075
  • 4
  • 24
  • 44