django中的inclusion_tag配置和实现
1 ### 2 在settings.py中设置libraries 3 ### 4 TEMPLATES = [ 5 { 6 'BACKEND': 'django.template.backends.django.DjangoTemplates', 7 'DIRS': [os.path.join(BASE_DIR, 'templates')], 8 'APP_DIRS': True, 9 'OPTIONS': { 10 'context_processors': [ 11 'django.template.context_processors.debug', 12 'django.template.context_processors.request', 13 'django.contrib.auth.context_processors.auth', 14 'django.contrib.messages.context_processors.messages', 15 ], 16 'libraries':{ 17 "manage_menu_list": "mac.templatetags.inclusion_tag_mac", 18 自定的tag函数 自定的tag函数的所在文件路径 19 }, 20 }, 21 }, 22 ] 23 24 25 26 ### 27 "mac.templatetags.inclusion_tag_mac"文件下自定的tag函数 28 ### 29 from django.template import Library 30 from django.urls import reverse 31 register = Library() 32 33 标签动态渲染 34 @register.inclusion_tag('manage_menu_list.html') 35 def manage_menu_list(request): 36 data_list = [ 37 {'title': '首页', 'url': reverse('mac_home')}, 38 {'title': '生成MAC', 'url': reverse('input_mac')}, 39 {'title': 'MAC下载', 'url': reverse('download_details')}, 40 ] 41 for item in data_list: 42 if request.path_info == item['url']: 43 item['class'] = 'active' 44 return {'data_list': data_list} 45 46 ### 47 在其他模板中首先导入文件inclusion_tag_mac 48 ### 49 {% load inclusion_tag_mac %} 50 .... 51 {% manage_menu_list request %} 52 ....