I'm trying to have my menus automatically change according to settings in my code so I don't have logic duplicated in my templates. Right now I use the route names to generate the urls with request.route_path(name)
and determine what the current page the user is on with request.matched_route.name
. My problem now is that I want to have different permissions on different views and automatically hide menu items that the user doesn't have permission to.
我正在尝试根据代码中的设置自动更改菜单,因此我的模板中没有重复的逻辑。现在我使用路由名称生成带有request.route_path(name)的URL,并使用request.matched_route.name确定用户当前页面的内容。我现在的问题是我想在不同的视图上拥有不同的权限,并自动隐藏用户没有权限的菜单项。
One of the major difficulties is that you can have multiple views for one route. But even if there's only one view associated with a route, I can't seem to find any simple way to retrieve it.
其中一个主要困难是您可以为一条路线提供多个视图。但即使只有一个与路径相关的视图,我似乎找不到任何简单的方法来检索它。
I'm using URL Dispatch. Is this something that'd only be do-able with traversal?
我正在使用URL Dispatch。这是否只能通过遍历来实现?
1 个解决方案
#1
0
Normally I use a combination of the following patterns for this:
通常我会使用以下模式的组合:
- My views are organized into classed
- 我的观点被组织成分类
- The base class has a basic
_menu
which is a list of(menu_title, route_name, params)
whereparams
is an optionally present dict. When in the template I can use amenu
property that builds the menu from the request and the above attribute. - 基类有一个基本的_menu,它是(menu_title,route_name,params)的列表,其中params是一个可选的存在的dict。在模板中,我可以使用菜单属性,根据请求和上述属性构建菜单。
- In the template create a function that iterates over theses entries, shows each but checks with something like
has_permission
if the view is actually allowed. - 在模板中创建一个迭代这些条目的函数,显示每个条目但是如果实际允许视图则使用has_permission之类的函数进行检查。
These ideas should get you started on a dynamic solution. It works fine for me, but it might require some more tweaking, for example, I attach another value "active" to the generated menu based on the current route.
这些想法应该让您开始动态解决方案。它对我来说很好,但它可能需要更多调整,例如,我根据当前路线将另一个值“激活”附加到生成的菜单。
#1
0
Normally I use a combination of the following patterns for this:
通常我会使用以下模式的组合:
- My views are organized into classed
- 我的观点被组织成分类
- The base class has a basic
_menu
which is a list of(menu_title, route_name, params)
whereparams
is an optionally present dict. When in the template I can use amenu
property that builds the menu from the request and the above attribute. - 基类有一个基本的_menu,它是(menu_title,route_name,params)的列表,其中params是一个可选的存在的dict。在模板中,我可以使用菜单属性,根据请求和上述属性构建菜单。
- In the template create a function that iterates over theses entries, shows each but checks with something like
has_permission
if the view is actually allowed. - 在模板中创建一个迭代这些条目的函数,显示每个条目但是如果实际允许视图则使用has_permission之类的函数进行检查。
These ideas should get you started on a dynamic solution. It works fine for me, but it might require some more tweaking, for example, I attach another value "active" to the generated menu based on the current route.
这些想法应该让您开始动态解决方案。它对我来说很好,但它可能需要更多调整,例如,我根据当前路线将另一个值“激活”附加到生成的菜单。