include Tag

Utility Most Useful

Documentation

Used to include one template in another.

Parent Template

{% block main %}
  <p>Content before include</p>
  {% include 'asides/book-ad.html' %}
  <p>Content after include</p>
{% endblock main %}

Included Template: templates/asides/book-ad.html

<aside>
  <p><strong>Read our Python Book!</strong></p>
</aside>

Result

<p>Content before include</p>
  <aside>
    <p><strong>Read our Python Book!</strong></p>
  </aside>
<p>Content after include</p>

Commentary

This should not be used to include headers and footers. Use Template Inheritance for that kind of thing. Use the include tag to include asides or callouts that show up on some, but not all pages.

Pagination Include

A great use case for the include tag is pagination, which could go on any ListView template. Here is a Bootstrap pagination nav:

<nav aria-label="pagination">
  <ul class="pagination justify-content-center">
    {% if page_obj.has_previous %}
      <li class="page-item">
        <a class="page-link" href="?page=1">&laquo; 1…</a>
      </li>
      {% if page_obj.previous_page_number != 1 %}
        <li class="page-item">
          <a class="page-link" href="?page={{ page_obj.previous_page_number }}">
            {{ page_obj.previous_page_number }}
          </a>
        </li>
      {% endif %}
    {% endif %}
    <li class="page-item active">
      <span class="page-link">
        {{ page_obj.number }}
      </span>
    </li>
    {% if page_obj.has_next %}
      {% if page_obj.next_page_number != page_obj.paginator.num_pages %}
        <li class="page-item">
          <a class="page-link" href="?page={{ page_obj.next_page_number }}">
            {{ page_obj.next_page_number }}
          </a>
        </li>
      {% endif %}
      <li class="page-item">
        <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">
          …{{ page_obj.paginator.num_pages }} &raquo;
        </a>
      </li>
    {% endif %}
  </ul>
</nav>

The resulting nav will look like this:


Did we get something wrong? Is there a use case for the include tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Oct. 30, 2022, 1:22 p.m. EST