Skip to content

Commit

Permalink
Merge pull request #20 from hansegucker/activ-menu-item-related-url
Browse files Browse the repository at this point in the history
Mark menu items as selected if a related URL is in path
  • Loading branch information
MiltonLn committed Nov 16, 2020
2 parents 7e1c772 + c4b6906 commit 5a4149f
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 10 deletions.
2 changes: 1 addition & 1 deletion AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ Val Kneeman under the name [django-menuware](https://github.com/un33k/django-men
* Milton Lenis - miltonln04@gmail.com

## Contributors:
None yet. Why not be the first?
* Jonathan Weth - dev@jonathanweth.de
5 changes: 5 additions & 0 deletions docs/authors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,8 @@ Authors
`Milton Lenis <https://github.com/MiltonLn>`__ - miltonln04@gmail.com

`Juan Diego García <https://github.com/yamijuan>`__ - juandgoc@gmail.com

Contributors
============

`Jonathan Weth <https://github.com/hansegucker>`__ - dev@jonathanweth.de
3 changes: 3 additions & 0 deletions docs/menugeneration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Django Menu Generator uses python dictionaries to represent the menu items, usua
"icon_class": 'some icon class',
"url": URL spec,
"root": True | False,
"related_urls": [ list of related URLs ],
"validators": [ list of validators ],
"submenu": Dictionary like this
}
Expand All @@ -22,6 +23,8 @@ Where each key is as follows:

- ``url``: See :doc:`urls`

- ``related_urls``: If one of this URLs is part of the path on the currently opened page, the menu item will be marked as selected (format of URLs like described at :doc:`urls`)

- ``root``: A flag to indicate this item is the root of a path, with this you can correctly mark nested menus as selected.

- ``validators``: See :doc:`validators`
Expand Down
29 changes: 20 additions & 9 deletions menu_generator/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import django
from django.core.exceptions import ImproperlyConfigured
from .utils import get_callable
from .utils import get_callable, parse_url

if django.VERSION >= (1, 10): # pragma: no cover
from django.urls import reverse, NoReverseMatch
Expand Down Expand Up @@ -74,22 +74,33 @@ def _get_url(self, item_dict):
Given a menu item dictionary, it returns the URL or an empty string.
"""
url = item_dict.get('url', '')
try:
final_url = reverse(**url) if type(url) is dict else reverse(url)
except NoReverseMatch:
final_url = url
return final_url
return parse_url(url)

def _get_related_urls(self, item_dict):
"""
Given a menu item dictionary, it returns the relateds URLs or an empty list.
"""
related_urls = item_dict.get('related_urls', [])
return [parse_url(url) for url in related_urls]

def _is_selected(self, item_dict):
"""
Given a menu item dictionary, it returns true if `url` is on path,
unless the item is marked as a root, in which case returns true if `url` is part of path.
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):
return url in self.path
if self._is_root(item_dict) and url in self.path:
return True
elif url == self.path:
return True
else:
return url == self.path
# Go through all related URLs and test
for related_url in self._get_related_urls(item_dict):
if related_url in self.path:
return True
return False

def _is_root(self, item_dict):
"""
Expand Down
45 changes: 45 additions & 0 deletions menu_generator/tests/test_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,48 @@ def test_generate_menu_no_visible_submenu(self):
nav = self.menu.generate_menu(list_dict)
self.assertEqual(len(nav), 1)
self.assertIsNone(nav[0]["submenu"])

def test_generate_menu_selected_related_urls_simple(self):
self.request.user = TestUser(authenticated=True)
self.request.path = "/persons/1/"
self.menu.save_user_state(self.request)
list_dict = [
{
"name": "parent1",
"url": "/user/account/",
"related_urls": ["/persons/", "/groups/"],
}
]
nav = self.menu.generate_menu(list_dict)

self.assertEqual(len(nav), 1)
self.assertEqual(nav[0]["selected"], True)

def test_generate_menu_selected_related_urls_submenu(self):
self.request.user = TestUser(authenticated=True)
self.request.path = "/persons/1/"
self.menu.save_user_state(self.request)
list_dict = [
{
"name": "parent1",
"url": "/user/account/",
"submenu": [
{
"name": "child1",
"url": '/user/account/profile/',
"related_urls": ["/persons/"]
},
{
"name": "child2",
"url": 'named_url',
"related_urls": ["/groups/"]
},
],
}
]
nav = self.menu.generate_menu(list_dict)

self.assertEqual(len(nav), 1)
self.assertEqual(nav[0]["selected"], True)
self.assertEqual(nav[0]["submenu"][0]["selected"], True)
self.assertEqual(nav[0]["submenu"][1]["selected"], False)
16 changes: 16 additions & 0 deletions menu_generator/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from importlib import import_module

import django
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured

if django.VERSION >= (1, 10): # pragma: no cover
from django.urls import reverse, NoReverseMatch
else:
from django.core.urlresolvers import reverse, NoReverseMatch

def get_callable(func_or_path):
"""
Expand Down Expand Up @@ -35,3 +40,14 @@ def clean_app_config(app_path):
"The application {0} is not in the configured apps or does" +
"not have the pattern app.apps.AppConfig".format(app_path)
)


def parse_url(url):
"""
Returns concrete URL for a menu dict URL attribute.
"""
try:
final_url = reverse(**url) if type(url) is dict else reverse(url)
except NoReverseMatch:
final_url = url
return final_url

0 comments on commit 5a4149f

Please sign in to comment.