Access StructBlock in a StreamField of a Page.get_children in Wagtail

拈花ヽ惹草 提交于 2019-12-13 03:54:24

问题


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


回答1:


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.




回答2:


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 ?



来源:https://stackoverflow.com/questions/48973531/access-structblock-in-a-streamfield-of-a-page-get-children-in-wagtail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!