方法一:在templatetags中的函数添加如下代码
1 # from django.template import Library 2 # from django.conf import settings 3 # 4 # register = Library() 5 # 6 # 7 # @register.inclusion_tag('menu.html') 8 # def unicom_menu(request): 9 # role = request.unicom_role 10 # menu_list = settings.UNICOM_MENU[role] 11 12 for row in menu_list: 13 if row['url'] == request.path_info: 14 row['class'] = "active" 15 else: 16 row.pop('class', None) 17 18 return {'menu_list': menu_list}
这种方法会导致没被选中的class值被删除
方法二:采用deepcoy方式
from django.template import Library from django.conf import settings import copy register = Library() @register.inclusion_tag('menu.html') def unicom_menu(request): role = request.unicom_role menu_list = copy.deepcopy(settings.UNICOM_MENU[role]) for row in menu_list: if row['url'] == request.path_info: row['class'] = "active" # else: # row.pop('class', None) return {'menu_list': menu_list}
标签:menu,list,request,添加,选中,import,导航条,role,row From: https://www.cnblogs.com/zhuangjoo/p/17428994.html