1

How do I output one random line of an array?

{% set img = [
  { bildli: 'http://i.giphy.com/I0xDz0htjsiME.gif' },
  { bildli: 'https://i.giphy.com/fA3JALhIi5YVa.gif' }
 ] %}
 {% for item in img %}
   <img src="{{ item.bildli }}" alt="">
 {% endfor %}

I tried {% for item in img.limit(1).order('RAND()') %} like you would on a normal entries.section but that doesn't work on array.

I also tried: {% for item in random(img) %} as statet in the twig doc but that doesn't work eyther. What's the catch here?

4

Take a look at the shuffle function provided by Craft: https://craftcms.com/docs/templating/functions#shuffle

This will shuffle the complete array and output them all in the new order:

{% set img = [
    { bildli: 'http://i.giphy.com/I0xDz0htjsiME.gif' },
    { bildli: 'https://i.giphy.com/fA3JALhIi5YVa.gif' }
] %}

{% set shuffledImages = shuffle(img) %}

{% for item in shuffledImages %}
    <img src="{{ item.bildli }}" alt="">
{% endfor %}

If you want to just output one random image, then this should work:

{% set img = [
    { bildli: 'http://i.giphy.com/I0xDz0htjsiME.gif' },
    { bildli: 'https://i.giphy.com/fA3JALhIi5YVa.gif' }
] %}

{% set randomImage = shuffle(img) | first %}

<img src="{{ randomImage.bildli }}" alt="">

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.