简体   繁体   中英

Array of images without repetitions in Twig

I have a lot of pictures in a directory ( more 25 pics ). With a PHP function, I list sources of pictures in an array ( listImg[] ) With Symfony, I return this array with a render twig.

I would like have 9 random pictures in Homepage and 12 pics for the About page..

The problem is the repetition of pictures...

My PHP function:

public function showImgDir(): array
    {
        $dir = "assets/img/tour";

        $ext_list = array("jpg", "jpeg", "png");
        $listImg = [];

        $picDir= opendir($dir);
        while ($file = readdir($picDir)) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            
            $listImg[] = $dir . '/' . $file;
        }
        closedir($picDir); 
        return $listImg;
    }

and in Twig:

{% for a in 1..9 %}
    <img src="{{random(listImg)|imagine_filter('mini')}}"/>
{% endfor %}

I want to use do.. while with twig to avoid repetition but I don't understand how can use the 'loop'

{% for a in 1..9 %}
    {{ loop.index }}  
{% endfor %}

Can you help me please? ( without JS solution for the moment )

Thank you:)

I use shuffle(array); before return

shuffle($listImg);
return $listImg;

and in twig:

{% for a in 1..9 %}
    <img src="{{listImg[a]|imagine_filter('mini')}}"/>
{% endfor %}

it works: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM