1

I have a block as follows:

class SomeBlock(blocks.StructBlock):
    choice = blocks.ChoiceBlock(choices=(('Y', 'Yellow'), ...))
    # more fields

    class Meta:
        template = 'myapp/blocks/some_block.html'

In my template I have:

{% load wagtailcore_tags %}
<div>{{ value.choice }}</div>

This would display 'Y' as expected but how do I get it to display as 'Yellow'?

These variations do not work (get no output):

{{ value.get_choice_display }}
{{ value.bound_blocks.get_choice_display }}
binadam
  • 13
  • 3

1 Answers1

0

Unfortunately there isn't a direct equivalent - Wagtail's blocks mechanism treats the display names as a detail that's specific to the edit form, rather than part of the data, so they're not easily accessible at the point where you're rendering the template. I'd suggest arranging things as follows:

  • Define the choice list in its own module where it can be imported from multiple places - e.g. myapp/colors.py:

    COLORS = (('Y', 'Yellow'), ...)
    COLORS_LOOKUP = dict(COLORS)  # gives you a dict of the form {'Y': 'Yellow', ...}
    
  • Update the ChoiceBlock definition to refer to the list defined there:

    from myapp.colors import COLORS
    
    class SomeBlock(blocks.StructBlock):
        choice = blocks.ChoiceBlock(choices=COLORS)
    
  • Create a custom template tag to do the lookup from value to display name - e.g. myapp/templatetags/color_tags.py:

    from django import template
    from myapp.colors import COLORS_LOOKUP
    
    register = template.Library()
    
    @register.simple_tag
    def get_color_display_name(name):
        return COLORS_LOOKUP.get(name)
    
  • Use this tag in your template:

    {% load color_tags %}
    ...
    {% get_color_display_name value.choice %}  {# to output it immediately #}
    {% get_color_display_name value.choice as label %}  {# to assign it to the variable 'label' #}
    
gasman
  • 23,691
  • 1
  • 38
  • 56