I already have a fk in the nav model referencing ‘self’, and using that to add some structure to navlinks. For example, being able to set parents and childs.
But what I’m after here, is a way to change the style (e.g. bold) the navlink which is currently active based on the viewed page. And where things get difficult is due to having pages which have the same root url as a navlink, but don’t exactly match the navlink url. For example, you can navigate to a navlink homepage, and then within that page, you run deeper into the url tree. But at the same time, you want to keep that same navlink homepage style bolded as you run deeper.
One way would be to use string matching via startswith. So, you can just match any urls which relate to that navlink by matching its root. But – I have multiple navlinks with the same root url. So, you’d be changing the style on multiple navlinks.
At the moment, I’m doing it like this. Which feels messy and wrong:
# dict of possible root url patterns seen by request.path (key) matched to corrent navlink url targets (items).
nav_active_target_patterns = {
r'^/page/page3/': '/page/page3/',
r'^/page/page2/page4/': '/page/page2/page4/',
}
self.sidenav_active_target = None
for link in nav_link_qs:
if link.target == request.path: # first look for an exact match over all possible navlinks
self.sidenav_active_target = link.target
break
for pattern, nav_active_target in self.nav_active_target_patterns.items():
if re.compile(pattern).match(request.path): # if no exact match, use pattern matching
self.sidenav_active_target = nav_active_target
break
So, for example, say I had /page/ as a possible navlink target within nav_link_qs, and the current request path was /page/. I’d be able to get that exact match and flag that navlink as currently active. Likewise for /page/page3/ and page/page2/page4/.
But say instead the user navigates to page/page3/, and then within that page, navigates to page/page3/subpage1/. I’d want to keep page/page3/ navlink active, but no longer have an exact match, as I don’t have a navlink for page/page3/subpage1/.