Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random string using Twig?

Tags:

php

twig

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:

  1. generating a default random code in the controller and then passing it to the view; or
  2. 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.

like image 742
Gustavo Straube Avatar asked Dec 06 '22 20:12

Gustavo Straube


2 Answers

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 }}
like image 179
Ryan Avatar answered Dec 09 '22 14:12

Ryan


Twig Native:

{{ random() }}

Visit below link for twig docs. [Check This]: https://twig.symfony.com/doc/3.x/functions/random.html

like image 32
Qcr Technologies Avatar answered Dec 09 '22 16:12

Qcr Technologies