Sort viewlets with the same weight by label
authorThierry Florac <thierry.florac@onf.fr>
Tue, 03 Apr 2018 15:21:30 +0200
changeset 15 3b4da52e3776
parent 14 f1f2277960c3
child 16 6376d1ff2918
Sort viewlets with the same weight by label
src/pyams_viewlet/manager.py
--- a/src/pyams_viewlet/manager.py	Sat Jan 27 00:41:05 2018 +0100
+++ b/src/pyams_viewlet/manager.py	Tue Apr 03 15:21:30 2018 +0200
@@ -9,6 +9,7 @@
 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
 # FOR A PARTICULAR PURPOSE.
 #
+from pyams_utils.request import check_request
 
 __docformat__ = 'restructuredtext'
 
@@ -159,6 +160,7 @@
 
 
 def get_weight(item):
+    """Get sort weight of a given viewlet"""
     name, viewlet = item
     try:
         return int(viewlet.weight)
@@ -166,11 +168,30 @@
         return 0
 
 
+def get_label(item, request=None):
+    """Get sort label of a given viewlet"""
+    name, viewlet = item
+    try:
+        if request is None:
+            request = check_request()
+        return request.localizer.translate(viewlet.label)
+    except AttributeError:
+        return '--'
+
+
+def get_weight_and_label(item, request=None):
+    """Get sort weight and label of a given viewlet"""
+    return get_weight(item), get_label(item, request)
+
+
 class WeightOrderedViewletManager(ViewletManager):
-    """Weight ordered viewlet managers."""
+    """Weight ordered viewlet managers.
+
+    Viewlets with the same weight are sorted by label
+    """
 
     def sort(self, viewlets):
-        return sorted(viewlets, key=get_weight)
+        return sorted(viewlets, key=lambda x: get_weight_and_label(x, request=self.request))
 
 
 def is_available(viewlet):