欢迎来到鹡鸰!
与 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 %}
这是做什么的:
- 循环通过 HomePage 的子页面(在此循环中标记为
parent)并打印 Page title: {title_here}
- 然后它将检查每个
parent循环迭代的子页面并打印- Child page title: {child_title}
这里有一个问题。这仅适用于 home_page.html 模板。一旦你转到/fruits/,它会尝试执行相同的逻辑,但这次它会认为Fruits 是新的HomePage
您可以从这里选择 2 个选项。
- 您可以为每个页面添加自定义上下文,以确保您始终传递
HomePage 并循环遍历它。这是最简单的方法,我将向您展示下面的代码。或者,
- 您可以使用 Django 模型创建菜单系统,并将菜单类注册为 Wagtail Snippet。如果您想深入了解 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 %}