Access StructBlock in a StreamField of a Page.get_

2019-08-21 07:37发布

I try to render a StreamField of a child page in a Page. I don't manage to render the different StructField within the StreamField. Here is my code

class DefinitionPage(Page):

body = StreamField([
    ('definition', blocks.StructBlock([
        ('heading', blocks.CharBlock(label='Titre')),
        ('paragraph', blocks.RichTextBlock(label='Paragraphe')),
    ]))
])

content_panels = Page.content_panels + [
    StreamFieldPanel('body'),
]

my template. (DefinitionPage is a child of this page.)

{% for post in page.get_children %}
    <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
    {% for block in post.body %}
        {% include_block block %}
    {% endfor %}
{% endfor %}

post.title is ok but it's like there is no block in post.body. I tried so many things and {% include_block block %} is certainly wrong. I also tried to add a custom template for the StructBlock without success.

How can I do ? I am using Django 2.0 and wagtail 2.0 (I'm new to wagtail but I read the doc) Best regards

2条回答
爷、活的狠高调
2楼-- · 2019-08-21 08:07

Thank you I changed my code In the parent PageModel I added:

def get_context(self, request):
    context = super().get_context(request)
    definitions = self.get_children().specific()
    context['definitions'] = definitions
    return context

And now in my template:

{% for definition in definitions %}
    {% for block in definition.body %}
        {%  include_block block %}
    {% endfor %}
{% endfor %}

I also created a custom template for my definition (simple it's just en test):

{% load wagtailcore_tags %}

<div class="definition">
    <h2>{{ value.bound_blocks.heading }}</h2>
    {{ value.bound_blocks.paragraph }}
</div>

Thanks a lot

Just last questions: Is there a better practice ? .specific in template or in a custom get_context() ? Is it a good practice to add custom template to StructBlock ?

查看更多
smile是对你的礼貌
3楼-- · 2019-08-21 08:10

You need to use page.get_children.specific - get_children only returns the basic Page information common to all page types, which doesn't include the body field in DefinitionPage.

查看更多
登录 后发表回答