来自 StreamField Wagtail 的组块

Group blocks from StreamField Wagtail

我想要实现的目标在列表中会更容易解释。 例如

list_of_blocks=[1,2,3,4,5,6,7,8,9,10,11,12]
block_first_row = list_of_blocks[:3]
block_rest_rows = [list_of_blocks[i:i+4] for i in range(3, len(list_of_blocks), 4)]
block_rows = block_rest_rows.insert(0, list_of_blocks)

我想对 StreamField 中的块进行分组,并将它们显示在按这些行分组的模板中。 有没有办法在我的模型中做到这一点?或者我应该以某种方式在模板中做.. 我试过:

StreamField 的值是 StreamValue 类型的类列表对象。由于它不是一个真正的列表,它可能不支持切片——如果不支持,您可以通过使用 list(self.body)(其中 body 是您的 StreamField)将其转换为一个真正的列表来解决这个问题。执行此操作的好地方是页面的 get_context 方法:

def get_context(self, request):
    context = super().get_context(request)

    list_of_blocks = list(self.body)
    block_first_row = list_of_blocks[:3]
    block_rest_rows = [list_of_blocks[i:i+4] for i in range(3, len(list_of_blocks), 4)]
    block_rows = block_rest_rows.insert(0, block_first_row)
    context['block_rows'] = block_rows

    return context

然后您可以在模板中访问 block_rows

{% for block_row in block_rows %}
    <div class="row">
        {% for block in block_row %}
            render block as normal, with {% include_block block %} or otherwise
        {% endfor %}
    </div>
{% endfor %}