@@ -9,6 +9,12 @@ access from within your templates. This way you can have a menu for your main
9
9
navigation, another menu for logged in users, another menu for anonymous users,
10
10
etc.
11
11
12
+ .. note ::
13
+
14
+ Since we use the ``menu `` namespace you will get ``ImportError `` if you
15
+ have any files named ``menu.py ``, ensure you use a plural version:
16
+ ``menus.py ``
17
+
12
18
To define your menus you need to create a file named ``menus.py `` inside of the
13
19
app that you wish to hook menus up to. In the ``menus.py `` file you should
14
20
import the ``Menu `` and ``MenuItem `` classes from the ``menu `` package::
@@ -116,5 +122,58 @@ You can use it like::
116
122
117
123
{% with menu=menus.main %}{% include "bootstrap-navbar.html" %}{% endwith %}
118
124
119
- .. _menu __init__.py source file : https://github.com/fatbox/django-simple-menu/blob/master/menu/__init__.py
125
+
126
+ Check generalizations
127
+ ---------------------
128
+
129
+ If your application is dynamic enough, or complex enough, you may find that you
130
+ want to generalize your check logic based on a permissions model, or something
131
+ similar. To accomplish this you can create your own custom ``MenuItem ``
132
+ implementation with a ``check `` method.
133
+
134
+ This assumes you have a ``utils `` package.
135
+
136
+ ``utils/menus.py ``::
137
+
138
+ from django.core.urlresolvers import resolve
139
+
140
+ from menu import MenuItem
141
+
142
+
143
+ class ViewMenuItem(MenuItem):
144
+ """Custom MenuItem that checks permissions based on the view associated
145
+ with a URL"""
146
+
147
+ def check(self, request):
148
+ """Check permissions based on our view"""
149
+ is_visible = True
150
+ match = resolve(self.url)
151
+
152
+ # do something with match, and possibly change is_visible...
153
+
154
+ self.visible = is_visible
155
+
156
+
157
+ ``reports/menus.py ``::
158
+
159
+ from utils.menus import ViewMenuItem
160
+
161
+ from menu import Menu, MenuItem
162
+
163
+ from django.core.urlresolvers import reverse
164
+
165
+ # Since we use ViewMenuItem here we do not need to define checks, instead
166
+ # the check logic will change their visibility based on the permissions
167
+ # attached to the views we reverse here.
168
+ reports_children = (
169
+ ViewMenuItem("Staff Only", reverse("reports.views.staff")),
170
+ ViewMenuItem("Superuser Only", reverse("reports.views.superuser"))
171
+ )
172
+
173
+ Menu.add_item("main", MenuItem("Reports Index",
174
+ reverse("reports.views.index"),
175
+ children=reports_children))
176
+
177
+
178
+ .. _menu __init__.py source file : https://github.com/borgstrom/django-simple-menu/blob/master/menu/__init__.py
120
179
.. _Twitter Bootstrap Navbar Component : http://twitter.github.com/bootstrap/components.html#navbar
0 commit comments