1

Been at this a couple of hours and my head is scrambled. Wonder if anyone has already solved it and cares to share? I'm trying to paginate a list of entries grouped by day - showing 3 days worth of entries on each page. This is slightly different (I think) to other threads on SE. Here's where I'm at so far:

{% set allEntries = craft.entries.section('stories').with(['categories']).all() %}
{% set allEntriesByDay = allEntries|group(e => e.postDate|date('long')) %}
{% for day, entriesInDay in allEntriesByDay %}
    <h2>{{ day }}</h2>
    {% for entry in entriesInDay %}
        ...
    {% endfor %}
{% endfor %}
{% include "_includes/pagination" ignore missing %}
2

Based on this clever tweet, you can do this:

{% set allEntriesByDay = craft
  .entries()
  .section('stories')
  .orderBy('postDate DESC')
  .with(['categories'])
  .all() | group(e => e.postDate|date('long')) %}

{% set dataProvider = create({
  'class': 'yii\\data\\ArrayDataProvider',
  'allModels': allEntriesByDay,
  'pagination': {'pageSize': 3}}) %} {# Set the days per page here #}

{% set results = dataProvider.getModels() %}

{% set currentPage = dataProvider.getPagination().getPage() + 1 %}
{% set totalPages = dataProvider.getPagination().getPageCount() %}

{% if currentPage > 1 %}
  {% set prevPage = currentPage - 1 %}
{% endif %}
{% if currentPage < totalPages %}
  {% set nextPage = currentPage + 1 %}
{% endif %}

{% if results | length %}
  {% for day, entriesInDay in results %}
    <h2>{{ day }}</h2>
    {% for entry in entriesInDay %}
      {{ entry.title }} <br>
    {% endfor %}
  {% endfor %}
  <hr>
  <div>
  {% if prevPage is defined %}
    <a href="{{ url(craft.app.request.absoluteUrl, {'q': craft.app.request.get('q'), 'page': prevPage}) }}">< Previous page</a>
  {% endif %}

  {% if nextPage is defined %}
    <a href="{{ url(craft.app.request.absoluteUrl, {'q': craft.app.request.get('q'), 'page': nextPage}) }}"> - Next page ></a>
  {% endif %}
  </div>
{% endif %}
2
  • Superb! Thanks Oli.
    – Ian Ebden
    Mar 9 '20 at 15:42
  • I can't take the credit for this but thanks!
    – Oli
    Mar 9 '20 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.