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>
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.
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).
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..)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With