M
M
My joy2014-08-30 13:52:53
PHP
My joy, 2014-08-30 13:52:53

How to split a list into groups of X entries in twig?

Hello!
There is a list of cities, I pass it to twig as an associative array.
I would like to display it not directly as a list, but as a table with groups by the first letter. Is it possible to do this in twig or does it need to be done in php itself?
Would like something like:

А                        Б                  ...
Абакан                   Барнаул
Архангельск              Бийск
....                     ...                ...

and now like this:
{% for city in city_list %}
    <b><a href="/city/{{ city.city_id }}" title="Страница города {{ city.city_name }}">{{ city.city_name }}</a></b> ( {{ city.city_count }} )<br>
{% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-08-30
@t-alexashka

There are three options:
1) custom function. It's simple, the input is an array, the output is html. the simplest solution, but it is one-time. That is, either you inside the function will have to pervert with templates and other things, or just hardcode part of the HTML inside the function, which is not good. In the case of a markup change, you will have to flatter and edit the function. This is such a solution vlob.
2) macros with loops and ifs inside. Pros - easy to implement, all in templates. There is an opportunity for reuse in the future, it is easier to change the markup. Cons - the templates themselves are a little more complicated.
3) the coolest one, both in terms of performance and reusability, is to write your own new tag, something like index_table or something like that, inside which to define something like a template for which to draw this whole thing. Pros: reusable, can be issued as an extension and left to posterity. Just as everything will eventually compile to PHP code. everything will work very fast. Cons - very difficult to implement relative to other options. But you will understand with Twig and it can turn out cool.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question