Search code examples
djangomethodsfeature-extraction

How to extract a method from Django HTML?


My website (built with django) has pagination to not have to load too much content at once. The buttons to jump between the pages should always look the same. I found the following code on the internet which works great:

{% if is_paginated %}
    {% if page_obj.has_previous %}
        <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
        <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
    {% endif %}

    {% if page_obj.has_next %}
        <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
        <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
    {% endif %}
{% endif %}

Unfortunately I have to put this in each of my HTML files and have duplicated code. Is there a way to extract these few lines somewhere else and then only link to them in the respective HTML files?


Solution

  • You can write these in a specific file, for example pagination.html:

    <!-- pagination.html -->
    {% if is_paginated %}
        {% if page_obj.has_previous %}
            <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
            <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
        {% endif %}
    
        {% if page_obj.has_next %}
            <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
            <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
        {% endif %}
    {% endif %}
    

    Then you can use the {% include … %} template tag [Django-doc] to render this file in other templates:

    <!-- some-other-template.html -->
    <!-- ... -->
    {% include 'path/to/pagination.html' %}