【问题标题】:wagtail - menus how to include homepage as well?wagtail - 菜单如何包含主页?
【发布时间】:2018-07-04 03:37:16
【问题描述】:

wagtail bakerydemo 有一套不错的菜单,我也想包括主页。

Wagtail 期望页面是 home 的子节点,它位于根目录,而菜单遵循层次结构 -

所以如果我在 navigation_tags 中改变 top_menu

https://github.com/wagtail/bakerydemo/blob/master/bakerydemo/base/templatetags/navigation_tags.py#L42

获取这样的菜单项:

menuitems = (parent.get_siblings()).live().in_menu()

主页出现了,但菜单将其视为祖先,而不是平等。

知道如何更改它以使“家”与其直系子女相同吗?

【问题讨论】:

    标签: wagtail


    【解决方案1】:

    实现此目的的一种方法是在主页前添加一个新的menuitem

    假设您只将这个top_menu标签用于主菜单,您还可以假设传入标签的parent将始终是site_root,而这又是主页。

    唯一的变化是在menuitems的for循环之后和模板上下文返回之前。

    示例:更新了 navigation_tags.py

        @register.inclusion_tag('tags/top_menu.html', takes_context=True)
        def top_menu(context, parent, calling_page=None):
            menuitems = parent.get_children().live().in_menu()
            for menuitem in menuitems:
                menuitem.show_dropdown = has_menu_children(menuitem)
                # We don't directly check if calling_page is None since the template
                # engine can pass an empty string to calling_page
                # if the variable passed as calling_page does not exist.
                menuitem.active = (calling_page.url.startswith(menuitem.url)
                                   if calling_page else False)
            # assumes menu is only called with parent=site_root and is live + ignores `in_menu` field on homepage
            home_page = parent
            home_page.show_dropdown = False
            home_page.active = (
                # must match urls exactly as all URLs will start with homepage URL
                (calling_page.url == home_page.url) if calling_page else False
            )
            # append the home page (site_root) to the start of the menuitems
            # menuitems is actually a queryset so we need to force it into a list
            menuitems = [home_page] + list(menuitems)
            return {
                'calling_page': calling_page,
                'menuitems': menuitems,
                # required by the pageurl tag that we want to use within this template
                'request': context['request'],
            }
    

    注意:menuitems 实际上是一个queryset not a list,这意味着向它附加一个项目我们需要强制它成为一个列表。这可能不是最有效的方法,您可以调整 queryset query 以始终包含主页,但这可以完成工作。

    【讨论】:

    • 干杯,我会玩这个。
    • 太好了,我已经更新了它以使用 QuerySets 并尊重 in_menu 和 live(),我应该只更新上面的代码示例吗?
    • 是的。去吧。谢谢
    • 如果它不让你 - 也许只是为其他人来这个问题写一个新的答案。
    • 完成,我不知道子菜单会发生什么(或者它们是否/如何在这里工作)。
    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多