I’m experiencing a specific issue with Grav collections that seems to be triggered by the number of unpublished posts.
Template code:
{% set collection = blog.collection().published(true).order('date', 'desc') %}
{% for post in collection.slice(0, 1) %}
<!-- First post display -->
{% endfor %}
{% for post in collection.slice(1, 3) %}
<!-- Next 3 posts display -->
{% endfor %}
The pattern I’ve discovered:
- 6 posts total: Works fine with 1-2 unpublished posts, fails with 3+ unpublished posts
- 8 posts total: Works fine with 1-2 unpublished posts, fails with 3+ unpublished posts
- The error occurs regardless of the page limit configuration (tested with limit: 6 and limit: 8)
Error details:
array_rand(): Argument #1 ($array) cannot be empty
Location: /system/src/Grav/Common/Iterator.php in the random() method
What I’ve tried that DOESN’T work:
- Using blog.children.published(true).order(‘date’, ‘desc’) - same error
- Adding {% if collection|length > 0 %} checks
- Increasing the page limit configuration
My blog page configuration:
title: Blog
content:
items:
- '@self.children'
limit: 6
order:
by: date
dir: desc
pagination: true
url_taxonomy_filters: true
Questions:
- Why does reusing a collection variable cause this error when having 3+ unpublished posts?
- Is this related to iterator consumption when slicing collections multiple times?
- Could this be a bug in how Grav’s Iterator handles multiple slice operations?
Additional info:
- I’m not explicitly calling any random() methods in my template
- The error appears to be triggered internally by Grav’s collection processing
- The issue is reproducible and consistent with the 3+ unpublished posts threshold
- The problem seems specifically related to reusing the same collection variable multiple times
Environment:
- Grav version: v1.7.49.5
- PHP version: 8.1.33
Any insights would be greatly appreciated!