Skip to content
Advertisement

How to specify a template for a Snippet in a StreamField when using SnippetChooserBlock

I want to use a snippet in a StreamField:

@register_snippet
class Advert(models.Model):
    url = models.URLField(null=True, blank=True)
    text = models.CharField(max_length=255)

    def __str__(self):
       return self.text

class MyPage(Page):
    body = StreamField([('Snippet', SnippetChooserBlock(
                        target_model='web.Advert')])

my_page.html:

{% for block in page.body %}
    {% include_block block %}
{% endfor %}

However, when rendering the Advert it renders only the str representation of self.text. How can I specify a template layout for the snippet block, e.g. like a StructBlock?

There is no documentation for SnippetChooserBlock.

Advertisement

Answer

Like all block types, SnippetChooserBlock accepts a template argument that specifies the path to a template to render for that block:

class MyPage(Page):
    body = StreamField([('Snippet', SnippetChooserBlock(
                        target_model='web.Advert', template='blocks/advert.html')])

Within that template, the snippet instance is available as the variable value:

<div class="advert">
    <a href="{{ value.url }}">{{ value.text }}</a>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement