【问题标题】:Group blocks from StreamField Wagtail从 StreamField Wagtail 分组块
【发布时间】:2020-11-14 10:05:05
【问题描述】:

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

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 上按列表操作
  • 解构 StreamField.. 然后按列表操作

【问题讨论】:

    标签: python django wagtail wagtail-streamfield


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 2016-08-31
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多