我也想要一个自动生成的菜单,但只需要一级菜单,包括主页。可能我做了一些天真的事情,但它起作用了。我使用的是 Wagtail 2.5.1 和 Django 2.2.2。
我的 Wagtail 页面结构如下:
Home page
/ \
Blog About
/ | \
n_item n_item n_item
我正在使用Bootstrap4,所以这是我的base.html模板中的导航条:
{% with root_p=request.site.root_page %}
{# this is static item for home #}
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link {% if '/' == request.path %} active {% endif %}" href="{{root_p.url}}">{{root_p.slug}}</a>
</li>
{# Here I am looping home's childrens #}
{% for nav in root_p.get_children.live %}
{% if nav.show_in_menus %}
<li class="nav-item">
<a class="nav-link {% if nav.slug in request.path %} active {% endif %}" href="{{nav.url}}">{{nav.slug}}</a>
</li>
{% endif %}
{% endfor %}
</ul>
{% endwith %}
这是结果:
这是结果:
现在我可以更改slug,打勾/取消“显示在菜单中”,我的bootstrap菜单会反映这些更改。
编辑:
我的上一个回答没有解决菜单项的自定义顺序问题。我们可以按照页面模型中的标准字段“first_published_at”或按“title”名称进行字母排序来排序项目。但我需要将其自定义。因此,我在每个页面模型中添加了自定义整数字段。然后,wagtail用户可以使用“promote”选项卡更改菜单项的顺序。
我的当前页面结构如下:
Home
/ | \
Case studies Services Contact
我的页面模型:(仅服务示例)
class ServicesPage(Page):
template = "home/services.html"
max_count = 1
subpage_types = []
menu_order = models.IntegerField(default = 0, help_text = "Setup custom menu order")
promote_panels = Page.promote_panels + [
FieldPanel('menu_order'),
]
class Meta:
verbose_name = "Services"
verbose_name_plural = "Services"
这是每个页面模型的推广标签中的样子:
最后一步是编辑基础模板中的导航栏循环:
{% with root_p=request.site.root_page %}
{% for nav in root_p.get_children.specific.live|dictsort:"menu_order" %}
{% if nav.show_in_menus %}
<li class="nav-item {% if nav.slug in request.path %} active {% endif %}">
<a class="nav-link" href="{{nav.url}}">{{nav.title}}</a>
</li>
{% endif %}
{% endfor %}
{% endwith %}
我正在使用默认的Django模板过滤器
dictsort进行排序。
我猜这不是最好的方法,但它能够工作。