13

I have a slideshow with slide data managed in a Matrix field. How would I go about randomizing the data returned in the template so the slides show in a different order on each page load?

26

You can either have MySQL select the blocks in a random order using RAND():

{% set blocks = entry.myMatrixField.order('RAND()') %}

Or you can shuffle the blocks from Twig instead, using Craft’s shuffle() function:

{% set blocks = shuffle(entry.myMatrixField) %}

There’s not a major performance difference either way in most cases, however if you also want to limit the number of blocks, each method will give you different results.

For example, this will pick 3 blocks at random out of the entire set:

{% set blocks = entry.myMatrixField.limit(3).order('RAND()') %}

But this will always pick the first 3 blocks, and those 3 blocks will be displayed in a random order:

{% set blocks = shuffle(entry.myMatrixField.limit(3)) %}
2

There are two options for accomplishing this:

{% for block in shuffle(entry.matrixField) %}

or

{% for block in shuffle(entry.matrixField.find()) %}
  • I think these are very much the same. entry.matrixField.find() explicitly returns an array, but shuffle() will convert to an array anyway – Marion Newlevant Jun 12 '14 at 19:34

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.