NarūnasK
NarūnasK

Reputation: 4950

How to add computed variable to the wagtail StructBlock template context?

I want to compute some custom variable based on the other block values in the StructBlock and add this custom variable to the template context. Essentially I should be able to use this computed variable in the StructBlock template like so {{ value.custom }}.

Here's my StructBlock:

class BaseBlock(blocks.StructBlock):
    bool_fld = blocks.BooleanBlock(required=False, default=False)

    def get_context(self, *a, **kw):
        ctx = super().get_context(*a, **kw)
        ctx['custom'] = 1 if self.bool_fld else 0
        return ctx

And the error:

'BaseBlock' object has no attribute 'bool_fld'

Any ideas?

Upvotes: 4

Views: 2580

Answers (1)

gasman
gasman

Reputation: 25237

The get_context method on block objects receives the block value as its first argument - in the case of StructBlock, this is a dict-like object whose fields can be accessed as value['some_field'].

class BaseBlock(blocks.StructBlock):
    bool_fld = blocks.BooleanBlock(required=False, default=False)

    def get_context(self, value, parent_context=None):
        ctx = super().get_context(value, parent_context=parent_context)
        ctx['custom'] = 1 if value['bool_fld'] else 0
        return ctx

See also the get_context example at http://docs.wagtail.io/en/v2.0/topics/streamfield.html#template-rendering.

self.bool_fld won't work here, because Block instances do not hold values themselves - they just act as converters between different data representations. (If you've worked with Django form field objects like forms.CharField, blocks are very similar; both block objects and form field objects know how to render values passed to them as form fields, but they don't hold on to those values.)

Upvotes: 9

Related Questions