skip to Main Content

In PHP I would do this:

$menu_groups = array();
foreach($items as $item){
    $menu_id = $item['properties.menu_id'];
    
    if(!array_key_exists($menu_id, $menu_groups)) $menu_groups[$menu_id] = array();
    
    $menu_groups[$menu_id][] = $item;
}

How can I accomplish something similar in a Twig template?

2

Answers


  1. you can do like this :  
    {% set handledPeople = [] %}
        {% for person in people if person not in handledPeople %}
            <div class="colour_container">
                {% for p in people if p.colour == person.colour and p not in handledPeople %}
                    <p>{{ p.firstname }} {{ p.surname }} - {{ p.colour }}</p>
                    {% set handledPeople = handledPeople|merge([p]) %}
                {% endfor %}
            </div>
        {% endfor %}
    
    Login or Signup to reply.
  2. as @pippo said in the comment templates should not contain the logic for better maitainability and testability and also for good practice of Symfony framework with twig as template engine. but if you insisted on knowing how you can do it I tried to transform your code from PHP to Twig and it should maybe look something like

    {% set menu_groups = items|group('properties.menu_id') %}
    {% for menu_id, items in menu_groups %}
        <h2>MyMenuID : {{ menu_id }}</h2>
        <ul>
            {% for item in items %}
                <li>{{ item.name }}</li>
            {% endfor %}
        </ul>
    {% endfor %}
    

    if your group filter is not defined in your twig then maybe try to create one

    1. First yo go to your src/Twig.
    2. Create a new class that extends TwigExtensionAbstractExtension (check doc here click)
    3. Don’t forget to declare your filter class in config/services.yaml

    then your new filter class should be like

    public function getFilters()
    {
        return [
           new TwigFilter('group', [$this, 'groupArrayItemsBy']),
         ];
     }
    
    public function groupArrayItemsBy(array $array, string $property)
    {
        $result = [];
        foreach ($array as $item) {
            $key = $item[$property];
            if (!isset($result[$key])) {
               $result[$key] = [];
            }
            $result[$key][] = $item;
        }
        return $result;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search