I have an input that holds the code for a coupon. Users can fill in a custom code, but I'd like to give them a default code. I have the following code now:
<input type="text" name="code" value="{{ form.code|default(RANDOM_CODE) }}">
And I want to replace RANDOM_CODE by a random string.
I don't think that is relevant to the question, but form.code contains the original coupon code. I use the same form for editing.
According to Twig docs, it's possible to generate random numbers using random(), or even get a random char from within a string using random('abcdefgh...'), but I'd like to generate a random string with a specific length.
I know that I can do that using at least two approaches:
- generating a default random code in the controller and then passing it to the view; or
- creating a Twig extension with a function to generate the random string for me.
Knowing that I'm curious if there is a way to generate a random string using only Twig's built-in functions.
forloop giving a range, like{% for i in 0..10 %}to create a string with 10 characters in length, for instance. But using this approach I'll need to add arandom('abcdefghi...')inside the loop. I was thinking in something more compact, but I'm almost sure it's not possible. - Gustavo Straube{% set code='prefix-' ~ random() %}. Do length by using a range. 10 characters? 'prefix-' is 7, need 3 more...random([100..999])- random number with 3 digits. - mindfullsilence