djangowagtailwagtail-streamfield

Wagtall - template class for blocks StreamField


I have a Strucktblock:

# blocks.py
class GameBlock(StructBlock):
    logo = ImageChooserBlock(required=True)
    image = ImageChooserBlock(required=True)
    heading = CharBlock(required=True, max_length=50)
    description = CharBlock(required=True, max_length=100)
    url_button = URLBlock(required=True)

    class Meta:
        icon = "form"
        template = "blocks/game_card.html"

How can I wrap one or more blocks in a template into its own class? For example:

<div class="row-grid">
  <div class="card">Card1</div>
  <div class="card">Card2</div>
</div>

I tried a template:

{% for block in page.body %}
  {% if block.block_type == 'game' %}
    <div class="row-grid">{% include_block block %}</div>
  {% else %}
    {% include_block block %}
{% endfor %}

And I did:

<div class="row-grid"><div class="card">Card1</div></div>
<div class="row-grid"><div class="card">Card2</div></div>

Solution

  • It looks to me like your template code did exactly what it was asked to do - wrap all cards in <div class="row-grid">. If you want markup associated with a group of cards, you may need to create a wrapper block for that something like:

    class GameGrid(StructBlock):
        grid = blocks.ListBlock(GameCard)
    
        class Meta:
            template = "blocks/game_grid.html"
    

    See these docs for details: https://docs.wagtail.org/en/latest/topics/streamfield.html#listblock