如何在 Wagtail 的侧边菜单部分中生成页面列表?

How do I generate a list of pages in the sections for a sidemenu in Wagtail?

我是 Wagtail 的真正初学者。如何在 Wagtail 的侧边菜单部分中生成页面列表?

我有以下站点结构,例如:

home/
    fruits/
        apples/
        oranges/
        grapes/
    vegetables/
        kale/
        spinach/
        cabbage/

home是使用home_page.html模板的HomePage类型,所有子页面都是使用content_page.html模板的ContentPage类型。

我想为所有内容页面制作一个侧边菜单,列出其组中的所有页面。例如,这个列表:

Fruits
Apples
Oranges
Grapes

应该是 fruitsappleorangesgrapes.

页面的侧边菜单 模板中的

page.get_children 只列出页面是否有子页面,因此,在这种情况下,只有 fruitsvegetables.

我将如何制作那个副菜单?

Wagtail 文档中的示例似乎暗示我不能只有像 ContentPage 这样的通用内容类型来获得我想要的那种列表,是这样吗?

非常感谢!

欢迎来到 Wagtail!

与 Web 开发中的大多数事情一样,有几种方法可以做到这一点。刚开始时最容易理解的是通过模板完成所有这些操作。所以在你的 home_page.html 中你可以有:

{% for parent in page.get_children %}
    Page title: {{ parent.title }} <br />

    {% if parent.get_children.count %}
        {% for child in parent.get_children %}
            - Child page title: {{ child.title }}<br/>
        {% endfor %}
    {% endif %}
{% endfor %}

这是做什么的:

  1. 循环 HomePage 的 child 页(在此循环中标记为 parent)并打印 Page title: {title_here}
  2. 然后它将检查每个 parent 循环迭代的 child 页并打印 - Child page title: {child_title}

这里有一个陷阱。这仅适用于 home_page.html 模板。一旦你转到 /fruits/,它会尝试执行相同的逻辑,但这次它会认为 Fruits 是新的 HomePage

您可以从这里选择 2 个选项。

  1. 您可以向每个页面添加自定义上下文,以确保您始终传入 HomePage 并循环遍历它。这是最简单的方法,我将向您展示下面的代码。或者,
  2. 您可以使用 Django 模型创建菜单系统并将菜单 class 注册为 Wagtail 代码段。如果您想更深入地了解 Wagtail,我有一个包含所有源代码的视频 (https://www.youtube.com/watch?v=Y8a9ROUUJXU)

要将 HomePage 添加到每个 ContentPage,您可以将其添加到每个页面的上下文中,如下所示:

class ContentPage(Page):

    # Fields here

    def get_context(self, request, *args, **kwargs):
        """Adding HomePage to your page context."""
        context = super().get_context(request, *args, **kwargs)
        context["home_page"] = HomePage.objects.first()
        return context

然后在您的模板中编写:

    {% for child_page in home_page.get_children %}
        Page title: {{ child_page.title }} <br />

        {% if child_page.get_children.count %}
            {% for grandchild_page in child_page.get_children %}
                - Child page title: {{ grandchild_page.title }}<br/>
            {% endfor %}
        {% endif %}
    {% endfor %}

编辑: 如果你在一个宏伟的child页面上,比如/fruits/apples/并且想要显示parent页面标题,以及所有同级页面(即 /fruits/oranges//fruits/grapes/),您可以循环浏览同级页面。这样的事情应该有效:

<!-- On `/fruits/` this will be the Home Page title. On `/fruits/apples/` this will be the Fruits page title. -->
<h2>{{ self.get_parent.title }}<h2>

{% for sibling in self.get_siblings %}
   <a href="{{ sibling.url }}">{{ sibling.title }}</a>
{% endfor %}