我是Wa的真正初学者。如何在Wagtail中的侧菜单中生成页面列表?
我以以下网站结构为例:
home/
fruits/
apples/
oranges/
grapes/
vegetables/
kale/
spinach/
cabbage/
home
使用HomePage
模板为home_page.html
类型,所有子页面使用ContentPage
模板为content_page.html
类型。
我想为所有内容页面制作一个侧面菜单,列出其组中的所有页面。例如,此列表:
Fruits
Apples
Oranges
Grapes
应该是页面fruits
,apple
,oranges
和grapes
的补充菜单。
page.get_children
仅列出页面中是否有子对象,因此,在这种情况下,仅列出fruits
和vegetables
。
我将如何制作该菜单?
Wagtail文档中的示例似乎暗示我不能仅拥有ContentPage
之类的通用内容类型来获得所需的列表,是真的吗?
谢谢你!
答案 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 %}
这是什么:
parent
)并打印Page title: {title_here}
parent
循环迭代的子页面并打印- Child page title: {child_title}
虽然这里有一个陷阱。这仅适用于home_page.html
模板。一旦您进入/fruits/
,它将尝试执行相同的逻辑,但是这次,它将认为Fruits
是新的HomePage
您可以从此处选择2个选项。
HomePage
并循环遍历。这是最简单的方法,下面将向您展示代码。或者,要将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 %}