简体   繁体   中英

Simple Math in Django template

I have a table setup in my templates with pagination and at the bottom left side it shows how many items are shown, like this:

在此处输入图片说明

Here 10 is called count and 19 is total .

If I go the next page ( as of now I have only 2 pages worth of data in my table ) it shows Showing 9 of 19 items .

I want to modify this slightly to show it as Showing 1 - 10 of 19 and then Showing 11 - 19 of 19 . It seems pretty simple algorithmically . All I have to do is initialize a variable start = 1 , print out the information as Showing {{start}} - {{count}} of {{total}} . Then when I go to the next page start = count +1 and count += count . However I have no Idea how to do this in a django template . I tried with the with tag as {%with start = 1%} but it gives me an error 'with' expected at least one variable assignment

This is where all the magic happens:

{% if table.page %}
        {% with table.page.paginator.count as total %}
            {% with table.page.object_list|length as count %}
                {% with start = 1 %}
                    {% block pagination %}
                        <ul class="pagination">
                            {% block pagination.cardinality %}
                                <li class="cardinality">
                                    {% if total != count %}
                                        {% blocktrans %}
                                            Showing {{ count }} of {{ total }}
                                        {% endblocktrans %}
                                    {% else %}
                                        {{ total }}
                                    {% endif %}
                                    {% if total == 1 %}
                                        {{ table.data.verbose_name }}
                                    {% else %}
                                        {{ table.data.verbose_name_plural }}
                                    {% endif %}
                                </li>
                            {% endblock pagination.cardinality %}
                        </ul>

You don't need to do maths for this. The page object already gives you the relevant information: start_index and end_index .

So:

{% with table.page as page %}
Showing {{ page.start_index }} - {{ page.end_index }} of {{ page.paginator.count }}
{% endwith %}

Plus, you can use page.has_other_pages to determine if there are other pages, rather than your complex logic comparing the total with the current count.

See the pagination docs .

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