'using random function but it's displaying duplicates
I am using the random function in twig and it is randomizing the images I need but it is repeating the logos. How can I make it so that the images are not repeated but are still randomized?
this is my code
{% set listItems = block.logos %}
{% for item in listItems %}
{% set item = random(listItems) %}
{% endfor %}
block.logos refers to the logos that i have implemented in block called logos. There is a field in the block in which i can add multiple images/logos in the block. i have about 20 logos.
Solution 1:[1]
You can use the PHP array_rand function.
array_rand($listItems, 1);
.
If your array is a key value array and your need the value use the returned key as index for get the image.
$index = array_rand($listItems, 1);
print_r($listItems[$index]);
Solution 2:[2]
If I understand this correctly: you have a list of images, and want to display them in a random order without displaying the same image twice.
Ideally you could implement a custom twig function based on the php function: shuffle. However for a quick solution, you could randomly sort an array.
{% set listItems = block.logos|sort((a, b) => random() <=> random()) %}
{% for item in block.logo %}
{{ item }}
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Maik Lowrey |
Solution 2 | Andrew Mellor |