Generate random letters using Jinja for cookiecutter template

1.1k views Asked by At

I am looking to generate a random 8 letter hash for a cookeicutter template. In pure Python, this would generate what I'd like:

In [3]: import random
In [3]: import string
In [4]: ''.join(random.choice(string.ascii_lowercase) for i in range(8))                                                                                        
Out[4]: 'jrqcwtav'

In Jinja, the closest thing I could find would be a multiline solution. I need a one-liner. Any ideas?

2

There are 2 answers

0
Nelson G. On BEST ANSWER

If you're using cookiecutter>=1.7, you can use filter random_ascii_string like this :

{{ random_ascii_string(8) }}

More information available about random_ascii_string.

0
Ilya On

In plain Jinja2 you can achieve the same using

{% macro random_string(len) -%}{% for i in range(0,len) -%}{{ [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]|random }}{% endfor %}{%- endmacro -%}
{% macro random_guid() -%} {{ random_string(8) + "-" + random_string(4) + "-" + random_string(4) + "-" + random_string(4) + "-" + random_string(12) }}{%- endmacro -%}
{% set myGUID = random_guid() %}

More info here: https://isbyr.com/create-random-guid-with-jinja/