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:
Knowing that I'm curious if there is a way to generate a random string using only Twig's built-in functions.
This code will generate a 10 character password in base64 (A to Z in lower and uppercase, 0 to 9, and dash and underscore). This also makes it url friendly. You can change the parameters to your liking if you like.
{% set randomPassword = [] %}
{% set alpha = 'abcdefghijklmnopqrstuvwxyz' %}
{% set numbers = '0123456789' %}
{% for i in 1..10 %}
{% set randomCharacter = random(alpha ~ alpha|upper ~ numbers ~ '-_') %}
{% set randomPassword = randomPassword|merge([randomCharacter]) %}
{% endfor %}
{% set randomPassword = randomPassword|join %}
{{ randomPassword }}
Twig Native:
{{ random() }}
Visit below link for twig docs. [Check This]: https://twig.symfony.com/doc/3.x/functions/random.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With