在Django中,如何根据屏幕大小将模型列表分为行和列?

2024-09-26 22:55:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个模型列表分解成行和列,我正在使用forloop遍历这些行和列

我试过了

{% if forloop.counter|divisibleby:4 %}
<div class="row m-3">
    <div class="col-12">
        <div class="row mt-3">
        {% for Collection in object_list %}

        {% if forloop.counter|divisibleby:4 %}
        <div class="row mt-3">
        {% endif %}
           <div class="col-6 col-sm-3">
               <div class="dark">
               <a>
                   <div style="background-image:url({{ Collection.img }})" class="Collection">
                       </div>
                       <h3 class="title-banner text-center">{{ Collection.Name }}</h3>
               </a>
            </div>
               </div>

{% if forloop.counter|divisibleby:4 %}
        </div>
        {% endif %}
{% endfor %}
            </div>
        </div>
</div>

我的问题就像How to display 2 thumbnails of span6 per row in Bootstrap with Django?

但是这个解决方案不适合我,因为它不允许我从html文件中更改groupby变量。我需要能够改变它,因为移动设备上只有两个列,计算机上只有4个列。有人可以编辑这个答案(第一个)并把它贴在这里,这样我就可以根据屏幕的不同从html文件中修改这个变量


Tags: 文件indivifhtmlcountercolh3
1条回答
网友
1楼 · 发布于 2024-09-26 22:55:39

您可以使用jinja2提供的slice() filter

考虑到您的代码:

<div class="row m-3">
    <div class="col-12">
        <div class="row mt-3">
        {% for Collection in object_list|slice(4) %}
           <div class="col-6 col-sm-3 {{ loop.index }}">
               {% for item in column %}
               <div class="dark">
               <a>
                   <div style="background-image:url({{ Collection.img }})" class="Collection"></div>
                   <h3 class="title-banner text-center">{{ Collection.Name }}</h3>
               </a>
            </div>
               {% endfor %}
               </div>
        {% endfor %}
        </div>
    </div>
</div>

您还可以查看batch filter,它允许您管理上一列中缺少的元素

相关问题 更多 >

    热门问题