Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break items into columns evenly in Jinja2 template

I have a list of cities names that is variable and I want to break it into 4 columns evenly. I have some solution but it looks overwhelmed and dirty. What's the best and simplest way to do it?

My solution is here:

{% set cities_in_column = cities|length/4|int %}
{% set step=0 %}
<div class="four columns">
    {% for city in cities|sort %}
        {% if step > cities_in_column %}
            {% set step = 0 %}
            </div>
            <div class="four columns">
        {% endif %}
        <h5><a href="/city/{{ city.url }}">{{ city.name }}</a> <span style="float:right;">({{ city.users_count }})</span></h5>
        {% set step=step + 1 %}
    {% endfor %}
</div>
like image 232
Sergei Basharov Avatar asked Jun 18 '12 09:06

Sergei Basharov


People also ask

What is the Jinja2 delimiters for expressions to print to the template output?

The default Jinja delimiters are configured as follows: {% ... %} for Statements. {{ ... }} for Expressions to print to the template output. {# ... #} for Comments not included in the template output.


2 Answers

You are looking for the slices filter:

{% for column in cities | sort | slice(4) -%}
<div class="four columns">
    {%- for city in column -%}
    <h5><a href="/city/{{ city.url}}">{{ city.name }}</a>
    <span style="float:right;">({{ city.users_count }})</span></h5>
    {%- endfor -%}
</div>
{%- endfor %}

There is also a complement to slices called batch that provides runs of n (rather than splitting up the iterable into n groups).

like image 63
Sean Vieira Avatar answered Nov 03 '22 10:11

Sean Vieira


This is a job for CSS*:

<ol style="column-count: 4;">
{% for city in cities|sort %}
    <li>
        <a href="/city/{{ city.url }}">{{ city.name }}</a> ({{ city.users_count }})
    </li>
{% endfor %}
</ol>

(*Be it column-count, float, flex, etc..)

like image 30
Jan Kyu Peblik Avatar answered Nov 03 '22 08:11

Jan Kyu Peblik