Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Display 3 random blog items

Started by Muut Archive 12 years ago · 9 replies · 654 views
12 years ago

Is there an easy way to get a collection of three random blog items inside a partial without a plugin?

12 years ago

Use taxonomy.find or page.parent.collection to get the list of pages. Then randomize filter to shuffle it. Then slice filter to shorten the list to length.

Sorry can't really type the code on my iPhone :)

12 years ago

Thanks for the fast reply! I was experimenting with taxonomy.find however I can't seem to randomize it. I'm probably doing the randomize wrong.

I used this for testing:

TWIG

{% set random_articles = taxonomy.findTaxonomy({'category':'blog'})|randomize %}
                    {% for post in random_articles %}
                        <li>{{ post.title }}</li>
                    {% endfor %}
--
12 years ago

Ok, this is even easier than I originally thought :)

TWIG
{% set random_articles = taxonomy.findTaxonomy({'category':'blog'}).random(3) %}

I had forgotten, so had to dig into the code. The trick was to look into the Collection class and see available methods. Not finding anything useful, I looked at the Iterator class which Collection extends. In there was a very handy random() method :)

12 years ago

Wow thanks! Didn't know you could give a value to random(), super easy!

12 years ago

Is there a similar method to get the 3 most recent articles in a partial?

12 years ago

it's not the same thing, but it can be done with a collection. Collections support sorting and ordering. something like:

TWIG
{% set recent_articles = page.find('/blog').collection.toArray|split(0,3) %}

Untested, but I think that should work.

12 years ago

Collection has also other useful functions like:

TXT
collection.nth(5)
collection.shuffle()
collection.slice(0, 3)
collection.append(second_collection)

So in this case I would just use:

TWIG

{% set recent_articles = page.find('/blog').collection.slice(0,3) %}
---
10 years ago

Just wondering. Did you get the display of 3 random articles to work? If so, is there some place I could look at it? I'm wrestling with the same problem myself, trying to surface and present one random article from the past (rather than a redirect with the Random plugin).

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1361 9 years ago
Archive · by Muut Archive, 9 years ago
2 939 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2958 9 years ago
Archive · by Muut Archive, 9 years ago
3 1123 9 years ago