【问题标题】:How to avoid "a lot of {%include%} gives a lot of <footer>"?如何避免“很多 {%include%} 给出很多 <footer>”?
【发布时间】:2021-12-12 12:26:55
【问题描述】:

当我需要在 html 模板中使用大量 {%include%}(内容)时 - 是否会为每个内容包含出现不必要的扩展?效果也适用于每个后续包含的内容...... 当我可以将内容包含添加到第一个 html 模板扩展器时,一切都很好。 但是当我使用“分页”时,我需要将“page=posts”发送到 paginator.html。我找不到将这个变量从 layout.html 发送到 blog.html 的方法... 而且我觉得以后我也会遇到同样的问题,所以应该解决。

layout.html

<div class="container body-content">
        <div id="content">
            {% block content %}
            {% endblock %}
        </div>
    </div>

    <div class="container body-content">
        <footer>
            <hr/>
            <p>&copy; {{ year }}. Сайт</p>
        </footer>
    </div>

blog.html

{% extends "app/layout.html" %}
 <!--♕-->
{% block content %}
        <h2>{{ title }}</h2><br>

        {% for post in posts %}
        <hr>
        <div class="">
            <h2> {{post.title}} </h2>
            <p> {{post.posted}} </p>
        </div>
        <p>
            <a href="{% url 'blogpost' parametr=post.id %}">{{ post.description }}</a>
        </p>
    {% endfor %}

    {% include "app/pagination.html" with page=posts %}

{% endblock %}

分页.html

{% extends "app/blog.html" %} 
 <!--♕-->
{% block content %} 
    <div class="pagination">
        <span class="step-links">
            {% if page.has_previous %}
                <a href="?page={{ page.previous_page_number }}">Предыдущая</a>
            {% endif %}
            <span class="current">
                Страница {{ page.number }} из {{ page.paginator.num_pages }}
            </span>
            {% if page.has_next %}
                <a href="?page={{ page.next_page_number }}">Следующая</a>
            {% endif %}
        </span>
    </div>
{% endblock %}

【问题讨论】:

  • pagination.html中删除{% extends "app/blog.html" %}
  • 非常感谢。确实有效(但我以为我以前做过所有这些简单的事情......)

标签: html css django django-templates include


【解决方案1】:

分页应该是一个只呈现分页内容的文件,而不是围绕它的模板。

这意味着您实现了分页没有{% extends "app/layout.html" %},所以:

{# pagination.html, no extends or block #}
<div class="pagination">
    <span class="step-links">
        {% if page.has_previous %}
            <a href="?page={{ page.previous_page_number }}">Предыдущая</a>
        {% endif %}
        <span class="current">
            Страница {{ page.number }} из {{ page.paginator.num_pages }}
        </span>
        {% if page.has_next %}
            <a href="?page={{ page.next_page_number }}">Следующая</a>
        {% endif %}
    </span>
</div>

这将阻止pagination.html 呈现页眉、页脚和其他内容。然后,您可以简单地将分页导入为实用程序模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2019-03-27
    • 2021-08-23
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多