3

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?

NarūnasK
  • 4,564
  • 8
  • 50
  • 76

1 Answers1

7

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.)

gasman
  • 23,691
  • 1
  • 38
  • 56
  • 2
    Thanks, eventually I've figured that I can use `ctx['value']['bool_fld']`, but your method seems much cleaner. I don't think that I've seen what `get_context` is receiving in the `block` objects in the docs, so it would be nice to have it there. Perhaps I should contribute to `wagtail` with git PR by re-posting your answers :) – NarūnasK Apr 03 '18 at 19:50