【问题标题】:Break items into columns evenly in Jinja2 template在 Jinja2 模板中将项目均匀地分成列
【发布时间】:2012-06-18 09:02:10
【问题描述】:

我有一个可变的城市名称列表,我想将它平均分成 4 列。我有一些解决方案,但它看起来不堪重负和肮脏。最好和最简单的方法是什么?

我的解决方案在这里:

{% 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>

【问题讨论】:

标签: python flask jinja2


【解决方案1】:

您正在寻找slices 过滤器:

{% 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 %}

还有一个对slices 的补充,称为batch,它提供n 的运行(而不是将迭代拆分为n 组)。

【讨论】:

    【解决方案2】:

    这是 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>
    

    (*是column-count, float, flex, 等等..)

    【讨论】:

    • 如何让css生成需要的html?需要在模板中完成
    • @cstrutton 您只需要 HTML 中的(完整的)项目,这就是我的答案中提供的示例中 for 循环所做的。此处的其他方法不必要地使用 Django 的模板语言将项目按要求分为四列,但仅 CSS 就可以做到这一点,而且代码和工作量要少得多。
    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2011-11-30
    相关资源
    最近更新 更多