简体   繁体   中英

Generate random strings in Twig that don't repeat

I'd like to generate (at least) two different random strings that are always different from each other.

{% set firstColour = random(['coral', 'pink', 'black', 'sand']) %}
{% set secondColour = random(['coral', 'pink', 'black', 'sand']) %}


{{ firstColour }} 
{{ secondColour }}

I thought an "easy" solution would be to reset the second color if it is equal to the first

{# before variables are called #} 
{% if firstColour == secondColour %}
    {% set secondColour = '' %}
    {% set secondColour = random(['coral', 'pink', 'black', 'sand']) %}
{% endif %}

Not only doesn't this seem very practical or "clean", but it also just doesn't work. On the twig documentation or other threads, I can't find anything about setting random strings with exceptions.

It's important that the outcome is random (not a slice) and not equal to the other variables. Eventually, I would like to get all possibilities in a random order with separate variables on the same page,

without ever repeating one: {{ firstColor}} {{ secondColour }} {{ thirdColour }} {{ fourthColour }} when called on a page, would always return 4 different values.

Is there a way to achieve using Twig's built-in functions or extensions?

Although I would agree with the comments you got to actually achieve this in a PHP controller of some sort, and that twig is meant for templating and not for those kind of logic, here is a possible solution.

What you could do is to create a randomColours array, and then filter out the array of colours you have based on what has already been added to the randomColours one.

Here would be the resulting code to display four colours:

{% set colours = ['coral', 'pink', 'black', 'sand'] %}
{% set randomColours = [] %}
{% for i in 1..colours | length %}
  {% set randomColours = randomColours | merge([random(colours | filter(value => value not in randomColours))]) %}
{% endfor %}

{% for colour in randomColours %}
 {{ colour }}
{% endfor %}

If you want only two like in your initial example, you can just switch from

{% for i in 1..colours | length %}

to

{% for i in 1..2 %}

Here is the twig fiddle for four colours: https://twigfiddle.com/ahtcuo
And here is the one for only two: https://twigfiddle.com/ahtcuo/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM