2

I have a single that has 5 banner images. I would like to load a different image each time the page loads. I want to do this with twig not JS, is this possible if so could somone point me in the right direction.

Thanks in advance

3 Answers 3

6

Simply using 'RAND()' in the order parameter does the trick.

{% for image in entry.banner.limit(1).order('RAND()') %}
  {{ image.url }}
{% endfor %}
0
4

I wanted to see if the same thing could be accomplished using Craft's shuffle function. At first, I was looping through the image array and using an if statement to grab the first one:

{% for image in shuffle(entry.banner) %}
    {% if loop.first %}
        {{ image.url }}
    {% endif %}
{% endfor %}

Then, I realized there was a less verbose option:

{% set image = shuffle(entry.banner)[0] %}
{{ image.url }}
3

Another way of getting a random image from image set in Craft 3

{{ shuffle(entry.bgImg.all())[0].getUrl('1900x1050') }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.