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.
CodePudding user response:
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 >
<a href="{{ value.url }}">{{ value.text }}</a>
</div>