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

时间:2019-04-23 20:16:54

标签: django-models django-templates wagtail

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

我以以下网站结构为例:

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

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

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

Fruits
Apples
Oranges
Grapes

应该是页面fruitsappleorangesgrapes的补充菜单。

模板中的

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

我将如何制作该菜单?

Wagtail文档中的示例似乎暗示我不能仅拥有ContentPage之类的通用内容类型来获得所需的列表,是真的吗?

谢谢你!

1 个答案:

答案 0 :(得分:0)

欢迎来到Wa!

与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的子页面(在此循环中标记为parent)并打印Page title: {title_here}
  2. 然后,它将检查每个parent循环迭代的子页面并打印- Child page title: {child_title}

虽然这里有一个陷阱。这仅适用于home_page.html模板。一旦您进入/fruits/,它将尝试执行相同的逻辑,但是这次,它将认为Fruits是新的HomePage

您可以从此处选择2个选项。

  1. 您可以向每个页面添加自定义上下文,以确保始终传递HomePage并循环遍历。这是最简单的方法,下面将向您展示代码。或者,
  2. 您可以使用Django模型创建一个Menu系统,并将Menu类注册为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 %}

编辑::如果您位于孙子页面上,例如/fruits/apples/,并且要显示父页面标题以及所有同级页面(即/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 %}
相关问题