Search code examples
wordpresspaginationtwigtimber

Pagination not working correctly with Twig


I'm using Twig inside WordPress within the Timber plugin and I have basically followed the layout they have used for pagination here.

It displays fine and everything, but it appears the arguments aren't working correctly for this bit:

{% include 'partials/pagination.twig' with { pagination: posts.pagination({show_all: false, mid_size: 2, end_size: 1}) } %}

No matter what I set those arguments to it outputs every page; so if I have 10 pages it will print out all 10 page numbers; I don't want this, I'm trying to restrict it to 5.

What is wrong here?


Solution

  • You don't need to use the default pagination template, you can go full custom

    {% set pages_to_show = 5 %}
    {% set current = posts.pagination.current %}
    {% set max = current + (pages_to_show - 1) %}
    {% if max > posts.pagination.total %}
        {% set current = posts.pagination.total - (pages_to_show - 1)  %}
        {% set max = posts.pagination.total %}
    {% endif %}
    
    
    <div class="tool-pagination">
        {% if posts.pagination.prev %}
            <a href="{{posts.pagination.prev.link}}" class="prev {{posts.pagination.prev.link|length ? '' : 'invisible'}}">Prev</a>
        {% endif %}    
        <ul class="pages">
            {% for i in current..max %}
                <li>
                    {% if posts.pagination.pages[i].link %}
                        <a href="{{posts.pagination.pages[i].link}}" class="{{posts.pagination.pages[i].class}}">{{posts.pagination.pages[i].title}}</a>
                    {% else %}
                        <span class="{{posts.pagination.pages[i].class}}">{{posts.pagination.pages[i].title}}</span>
                    {% endif %}
                </li>
            {% endfor %}
            {% if posts.pagination.next %}
                <a href="{{posts.pagination.next.link}}" class="next {{posts.pagination.next.link|length ? '' : 'invisible'}}">Next</a>
            {% endif %}     
        </ul>
    </div>
    

    lightweight demo


    do not this is just a small example of how you could solve this