首页 > 解决方案 > 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 )

标签: phpsymfonytwig

解决方案


谢谢 :)

我使用 shuffle(array); 返回前

shuffle($listImg);
return $listImg;

在树枝中:

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

有用 !:)


推荐阅读