jazzband / wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
MIT License
398 stars 138 forks source link

Ability to add extra field to menu_item from page field #399

Closed andrewebdev closed 3 years ago

andrewebdev commented 3 years ago

What would be the best way to add a extra property to the some menu items? I had a look at the hooks, but there is no clear hook to do this.

My issue is that I have a property on some of my pages which should change the menu item CSS. These can change between pages. I can grab the page_id from the menu_item, do a lookup for that property on the page from there, but this will cause extra database queries that I'd prefer to avoid.

Correction: I cannot even look up page_id in the template using a filter because even this is not passed to the context.

I tried the following:

@hooks.register('menus_modify_base_page_queryset')
def menu_item_highlights(
        queryset,
        request,
        menu_instance,
        original_menu_tag,
        current_site,
        **kwargs):

    queryset = queryset.annotate(
        highlight_color=F('genericpage__highlight_color'))
    return queryset

But of course this doesn't work because, when the menu_items are primed, this value is not added. I just want a way to add highlight_color to the menu_item context.

ababic commented 3 years ago

@andrewebdev the page for a menu item should always be accessible from the template.

For top-level menu items, the the menu item will be a MenuItem instance, with the page available via the link_page field, so menu_item.link_page.highlight_color should work.

For menu items generated from pages, the menu items are actually specific page instances with attributes added, so menu_item.highlight_color should work.