Getting one random children page using TWIG

Hello,
how can I get only one random children from ‘item’ pages under ‘blog’ page using TWIG?

Can I modify this example from documentation?

    {% for post in page.find('/blog').children.order('date', 'desc').slice(0, 5) %}
  • {{ post.title }}
  • {% endfor %}

THANKS!

The Twig documentation mentions the random function, which you could use to simply wrap your expression above (forget the for loop):

random(page.find('/blog').children.order('date', 'desc').slice(0,5)).title or just random(page.find('/blog').children).title if you don;t need to select from the five latest.

Grav also adds a randomize Twig filter, which you could combine with the first filter to get a single random item, e.g. page.find('/blog').children|randomize|first and then you’d have select its title property.

1 Like

Ok, I did that, thank you.

One more question:
if i put TWIG code inside of a page by processing TWIG first, I noticed that my random item changes only sometimes. What exactly is the trigger to get new random item? Does it read from cache so item always stays the same?

How can I force it to show new item every time i refresh the page?

Thanks!

You may be about the first person to notice this! Try setting cache_enable: false in the page frontmatter to find out if it’s a cache problem. If it is, I was thinking that this is a bug, but on reflection it probably isn’t.

1 Like

Indeed it was cache! Now I get new item on every refresh. Is that ok? :slight_smile:

The main thing is you’re happy :slight_smile: