我可以通过重新定义完整的菜单结构来更改活动菜单项 在每个函数调用中,例如:
# default.py
def Item1():
response.menu=[['Item1',True,URL('Item1')],
['Item2',False,URL('Item2')]]
...
return locals()
def Item2():
response.menu=[['Item1',False,URL('Item1')],
['Item2',True,URL('Item2')]]
...
return locals()
是否有更紧凑的方式,例如
response.menu.activate(item1)
要这样做吗?
我可以在参数active_url
here上找到备注,但是我不知道如何使用它,找不到语法描述。
编辑:
我可能无法完全理解Anthony的回答,因为我无法运行它。因此,我现在已经以一种非常蛮力的方式修改了代码,以
# menu.py
response.menu=[['Item1',False,URL('Item1')],
['Item2',False,URL('Item2')]]
# default.py
def Item1():
response.menu[0][1]=True
...
return locals()
def Item2():
response.menu[1][1]=True
...
return locals()
我很确定还有一种我不知道的更优雅的方法。
答案 0 :(得分:1)
If you are using the MENU
helper, when you call it, you can specify the current URL as the active one:
MENU(response.menu, active_url=URL())
Note, URL()
with no arguments returns the part of the URL containing the application, controller, and function for the current request. URL(args=request.args)
also includes the current request.args
, and finally, URL(args=request.args, vars=request.get_vars)
additionally includes the query string of the current request. If your menu item URLs include args
or vars
, then you will need to pass those as the active_url
as well, or there will not be a match.
Alternatively, for each menu item, you can do something like:
current_url = URL(args=request.args, vars=request.vars)
response.menu = [
['Item1', URL('item1') == current_url, URL('item1')],
['Item2', URL('item2', args='arg1') == current_url, URL('item2', args1='arg1')],
...
]
To avoid the redundancy, you could try a helper like:
def menu_item(label, *args, **kwargs):
url = URL(*args, **kwargs)
return [label, url == URL(args=request.args, vars=request.get_vars), url]
response.menu = [
menu_item('Item1', 'item1'),
menu_item('Item2', 'item2', args='args1'),
menu_item('Item3', 'item3', args='args1', vars=dict(var1=1))
]
If you don't want to match the query string to determine the active URL, then exclude vars=request.get_vars
from the call to URL()
in menu_item
.