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?
2 Answers
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)) %}
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, butshuffle()
will convert to an array anyway Jun 12, 2014 at 19:34