0

Is there any way to check if a ListBlock is empty in a template (i.e. no child blocks)? Just doing:

{% if value.some_list_block_field %}

doesn't work.

Mark Horgan
  • 3,243
  • 4
  • 27
  • 28
  • If you add your block/page definition, I could adjust the example of the code in my answer to your specific use-case. – JanMalte Jul 25 '22 at 11:30

2 Answers2

0

Actually the above code does work but you have to make sure that empty children are deleted in the admin. It looks like one empty child is added by default.

Mark Horgan
  • 3,243
  • 4
  • 27
  • 28
0

You can set an empty list as explicit default value default=[],. Then the check in the template works as expected.

Wagtail adds an empty element as default to a ListBlock, therefor the list is not empty but contains an empty block element. If you set the default value explicit, this value will be used instead of the empty block.

class ExampleBlock(blocks.StructBlock):
    some_list_block_field = blocks.ListBlock(
        blocks.TextBlock(label="Text"),
        default=[],
    )

{% if value.some_list_block_field %}
  <!-- list is not empty -->
{% endif %}
JanMalte
  • 934
  • 6
  • 17