【问题标题】:Access StructBlock in a StreamField of a Page.get_children in Wagtail在 Wagtail 的 Page.get_children 的 StreamField 中访问 StructBlock
【发布时间】:2018-02-25 12:41:36
【问题描述】:

我尝试在页面中呈现子页面的 StreamField。我无法在 StreamField 中呈现不同的 StructField。这是我的代码

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'),
]

我的模板。 (DefinitionPage 是该页面的子页面。)

{% 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 没问题,但好像 post.body 中没有块。 我尝试了很多东西,{% include_block block %} 肯定是错误的。我还尝试为 StructBlock 添加自定义模板,但没有成功。

我该怎么办?我正在使用 Django 2.0 和 wagtail 2.0(我是 wagtail 的新手,但我阅读了文档) 最好的问候

【问题讨论】:

    标签: django wagtail wagtail-streamfield


    【解决方案1】:

    您需要使用page.get_children.specific - get_children 只返回所有页面类型共有的基本Page 信息,其中不包括DefinitionPage 中的body 字段。

    【讨论】:

    • 谢谢。我不知道.specific。所以我将 {% for post in page.get_children %} 更改为 {% for post in page.get_children.specific %} 但它似乎没有任何改变。
    • 我也尝试修改上下文def get_context(self, request): context = super().get_context(request) definitions = self.get_children().specific() context['definitions'] = definitions return context 并尝试{% for definition in definitions %}{% for block in definition %},但问题似乎是{% include_blocks block %}。你怎么看?
    • 好吧,不知何故,我删除了我所有的 DefinitionPage,所以没有什么可显示的......现在它可以与 {% for post in page.get_children.specific %} 一起使用,非常感谢!
    【解决方案2】:

    谢谢你我改变了我的代码 在我添加的父 PageModel 中:

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

    现在在我的模板中:

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

    我还为我的定义创建了一个自定义模板(很简单,只是在测试中):

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

    非常感谢

    最后一个问题:有更好的做法吗? .specific 在模板或自定义 get_context() 中?将自定义模板添加到 StructBlock 是一种好习惯吗?

    【讨论】:

      猜你喜欢
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多