Hi Matt,
There's no built-in way of doing that - ListBlocks are only designed to return blocks in the order they're set up in the editor.
To avoid cramming in too much logic in the template, I'd suggest defining a custom 'render' method on the block:
from django.template.loader import render_to_string
class StaffListingBlock(blocks.StructBlock):
staff_members = blocks.ListBlock(StaffMemberBlock())
ordering = blocks.ChoiceBlock(choices=[('manual', 'Manual'), ('first_name', "First name"), ('surname', "Surname")])
def render(self, value):
if value['ordering'] == 'first_name':
staff_members = sorted(value['staff_members'], key=lambda member: member['first_name'])
elif value['ordering'] == 'surname':
staff_members = sorted(value['staff_members'], key=lambda member: member['surname'])
else:
staff_members = value['staff_members']
return render_to_string(self.meta.template, {
'self': value,
'staff_members': staff_members,
})
# the staff_listing.html template now has access to 'self' and the sorted 'staff_members' list
class Meta:
template = 'myapp/blocks/staff_listing.html'
Cheers,
- Matt