简体   繁体   中英

Django:Html templates

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

您可以使用Inclusion标记实现navbar html模块,然后就无需在视图代码中将其传输给模板。

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

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