From f77cc68fc3b566ce0e46c30b706f57bff6baf054 Mon Sep 17 00:00:00 2001 From: Dominik George Date: Mon, 16 Nov 2020 23:22:02 +0100 Subject: [PATCH] Anchor related_url to beginning of request path and match components Closes #22. --- menu_generator/menu.py | 6 +++--- menu_generator/utils.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/menu_generator/menu.py b/menu_generator/menu.py index 276d76e..c4e54eb 100755 --- a/menu_generator/menu.py +++ b/menu_generator/menu.py @@ -2,7 +2,7 @@ import django from django.core.exceptions import ImproperlyConfigured -from .utils import get_callable, parse_url +from .utils import get_callable, parse_url, path_startswith if django.VERSION >= (1, 10): # pragma: no cover from django.urls import reverse, NoReverseMatch @@ -91,14 +91,14 @@ def _is_selected(self, item_dict): If related URLS are given, it also returns true if one of the related URLS is part of path. """ url = self._get_url(item_dict) - if self._is_root(item_dict) and url in self.path: + if self._is_root(item_dict) and path_startswith(self.path, url): return True elif url == self.path: return True else: # Go through all related URLs and test for related_url in self._get_related_urls(item_dict): - if related_url in self.path: + if path_startswith(self.path, related_url): return True return False diff --git a/menu_generator/utils.py b/menu_generator/utils.py index e67cde8..7329da8 100755 --- a/menu_generator/utils.py +++ b/menu_generator/utils.py @@ -52,3 +52,13 @@ def parse_url(url): except NoReverseMatch: final_url = url return final_url + + +def path_startswith(path, prefix): + """ + Returns True if the leftmost path components are the same as prefix. + """ + path_components = path.strip("/").split("/") + prefix_components = prefix.strip("/").split("/") + + return path_components[:len(prefix_components)] == prefix_components