From cde821a30a510f957f9e9150f2e44f981c5f716c Mon Sep 17 00:00:00 2001 From: Pim Vernooij Date: Mon, 12 Dec 2016 23:29:19 +0100 Subject: [PATCH] implement conditional rendering in block --- src/personalisation/blocks.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/personalisation/blocks.py b/src/personalisation/blocks.py index 105fa08..6f56113 100644 --- a/src/personalisation/blocks.py +++ b/src/personalisation/blocks.py @@ -3,10 +3,23 @@ from personalisation.models import Segment class PersonalisedStructBlock(blocks.StructBlock): - if Segment.objects.count() > 0: - segment = blocks.ChoiceBlock(choices=[ - (segment.pk, "{} ({})".format(segment.name, segment.status) ) \ - for segment in Segment.objects.all() + segment = blocks.ChoiceBlock(choices=[ + (segment.pk, "{} ({})".format(segment.name, segment.status) ) \ + for segment in Segment.objects.all() ], required=False, label="Personalisation segment", help_text="Only show this content block for users in this segment") + + def render(self, value, context=None): + """Only render block when the user is in the segment the block is + meant for""" + + user_segments = context['request'].session['segments'] + + if value['segment']: + for segment in user_segments: + if segment['id'] == int(value['segment']): + return super(PersonalisedStructBlock, self).render(value, + context) + + return ""