I want to use a snippet in a StreamField:
JavaScript
x
12
12
1
@register_snippet
2
class Advert(models.Model):
3
url = models.URLField(null=True, blank=True)
4
text = models.CharField(max_length=255)
5
6
def __str__(self):
7
return self.text
8
9
class MyPage(Page):
10
body = StreamField([('Snippet', SnippetChooserBlock(
11
target_model='web.Advert')])
12
my_page.html:
JavaScript
1
4
1
{% for block in page.body %}
2
{% include_block block %}
3
{% endfor %}
4
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:
JavaScript
1
4
1
class MyPage(Page):
2
body = StreamField([('Snippet', SnippetChooserBlock(
3
target_model='web.Advert', template='blocks/advert.html')])
4
Within that template, the snippet instance is available as the variable value
:
JavaScript
1
4
1
<div class="advert">
2
<a href="{{ value.url }}">{{ value.text }}</a>
3
</div>
4