Wagtail:在 parent 页面中显示 child 页面的列表

Wagtail: Display a list of child pages inside a parent page

在 Wagtail CMS 中,我正在尝试创建一个索引页面,该页面将显示其所有 child 页面的列表以及与每个 child 页面关联的特色图片。

我在models.py中创建了这两个页面模型:

class IndexPage(Page):
    intro = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
    ]

    subpage_types = ['myapp.ItemPage']


class ItemPage(Page):
    representative_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    body = RichTextField(blank=True)

    promote_panels = Page.promote_panels + [
        ImageChooserPanel('representative_image'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('body', classname='full'),
    ]

在模板index_page.html中,我添加了以下代码:

<div class="intro">{{ self.intro|richtext }}</div>

{% for page in self.get_children %}
  {{ page.title }}
  {% image page.representative_image width-400 %}
{% endfor %}

这会显示所有 child 页面标题,但不显示图像。是否可以检索 child 页面的图像字段?

我找到了这个解决方案:将函数 child_pages 添加到 IndexPage:

class IndexPage(Page):
    intro = RichTextField(blank=True)

    def child_pages(self):
        return ItemPage.objects.live().child_of(self)

    content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
    ]

    subpage_types = ['myapp.ItemPage']

这可以在模板中访问:

{% for page in self.child_pages %}
  {{ page.title }}
  {% image page.representative_image width-400 %}
{% endfor %}

来自release notes of wagtail version 1.1

Usually, an operation that retrieves a queryset of pages (such as homepage.get_children()) will return them as basic Page instances, which only include the core page data such as title. The specific() method (e.g. homepage.get_children().specific()) now allows them to be retrieved as their most specific type, using the minimum number of queries.

因此在即将发布的 1.1 版本中您不再需要自定义函数,您可以将模板更改为:

{% for page in self.get_children.specific %}
    {{ page.title }}
    {% image page.representative_image width-400 %}
{% endfor %}

至少从 0.8 版开始,以下内容也应该可以使用 specific:

{% for page in self.get_children %}
    {{ page.title }}
    {% image page.specific.representative_image width-400 %}
{% endfor %}