2

What is the best way to get a random number within a certain range?

I made something but I guess there is a better way:

In this example I want to position some elements randomly. This approach works, but I have to define a variable for each value.

{% set randomizr = range(10, 90) %}

{% set randomHeight1 = shuffle(randomizr) | first %}
{% set randomWidth1 = shuffle(randomizr) | first %}

{% set randomHeight2 = shuffle(randomizr) | first %}
{% set randomWidth2 = shuffle(randomizr) | first %}

{% set randomHeight3 = shuffle(randomizr) | first %}
{% set randomWidth3 = shuffle(randomizr) | first %}

{% set randomHeight4 = shuffle(randomizr) | first %}
{% set randomWidth4 = shuffle(randomizr) | first %}

{% set randomHeight5 = shuffle(randomizr) | first %}
{% set randomWidth5 = shuffle(randomizr) | first %}

<div class="sandbox">
    <div style="left: {{ randomHeight1 }}%; top: {{ randomWidth1 }}%;"></div>
    <div style="left: {{ randomHeight2 }}%; top: {{ randomWidth2 }}%;"></div>
    <div style="left: {{ randomHeight3 }}%; top: {{ randomWidth3 }}%;"></div>
    <div style="left: {{ randomHeight4 }}%; top: {{ randomWidth4 }}%;"></div>
    <div style="left: {{ randomHeight5 }}%; top: {{ randomWidth5 }}%;"></div>
</div>

Is this somehow possible without writing each variable manually?

2
  • I don't know what you're creating, but does it make sense to explore changing these values in JavaScript rather than directly in the markup? Commented Aug 5, 2016 at 14:09
  • Yeah I taught about that too but first I'd like to see if it's possible within twig.
    – KSPR
    Commented Aug 7, 2016 at 8:52

2 Answers 2

4

Building off of Brad's answer, you might consider using a for loop to render your markup, instead of setting all of those variables:

{% set range = range(10, 90) %}
{% set totalDivs = 5 %}

<div class="sandbox">
  {% for i in 1..totalDivs %}
    <div style="left: {{ random(range) }}%; top: {{ random(range) }}%;"></div>
  {% endfor %}
</div>
2

Instead of using shuffle, which is only available in the extra Array extensions library, you could just use random.

{% set range = range(10, 90) %}

{% set randomHeight1 = random(range) %}
{% set randomWidth1 = random(range) %}

{% set randomHeight2 = random(range) %}
{% set randomWidth2 = random(range) %}

...
2
  • 1
    There is this crazy cool CMS named Craft, that adds some Twig functions on top of the default ones and shuffle is one of them! ;-)
    – carlcs
    Commented Aug 6, 2016 at 15:07
  • I'll have to check it out sometime! :)
    – Brad Bell
    Commented Aug 6, 2016 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.