Django:Html 模板

2024-04-28 10:59:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我为另一个html编写了一个基本html

在基本.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 %}

我的导航栏从基本.html,但其他html扩展基本.html,无法正确显示导航栏,因为其他不能得到“subjectType”

我如何编码?在

我使用python3.6.5和django2.0


Tags: nameinurlforfoohtmltypelink
2条回答

主要的原因是你用不同的html从视图传递上下文。在

在扩展其他html时,包含或扩展的html将无法访问在模板中传递的上下文,因此需要重写模板中的特定块

可以使用以下模板:

基本.html

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

现在,如果从视图呈现home.html,它应该是:

主页.html

^{pr2}$

因此,如果您使用模板home.html传递上下文,则需要重写navbar才能使用context

此外,您还可以创建另一个html并在模板中包括:

导航栏.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 %}

主页.html

{% extends 'base.html' %}
<!  the blocks you override here only replaced  >
{% block navbar %}
    {% include 'navbar.html' %}
{% endblock %}

您可以使用Inclusion标记实现navbar html模块,然后不需要为视图中的模板代码传输它

相关问题 更多 >