Django 中所有应用程序共享的菜单
Posted
技术标签:
【中文标题】Django 中所有应用程序共享的菜单【英文标题】:Menu shared by all applications in Django 【发布时间】:2018-01-12 18:43:35 【问题描述】:我在 Django>1.9 中构建了一个 menu
作为 templatetag
。
问题是在这个solution之后,我不能把模板标签放在文件夹的根目录下,因为我得到了一个:
TemplateSyntaxError: 'menu' is not a registered tag library
下面是我修改过的settings.py
的部分:
TEMPLATES = [
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Look for base template at root of project
'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
'APP_DIRS': True,
'OPTIONS':
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
# Look for base templatetags at root of project
'libraries':
'project_tags': 'templatetags.menu',
,
,
]
即使使用如下所示的空 menu.py
模板标签,我也会遇到相同的错误:
from django import template
register = template.Library()
@register.inclusion_tag('menu.html', takes_context=True)
def menu(context):
pass
Django
是否支持项目范围的templatetags
?
【问题讨论】:
你有一个“templatetags”文件夹?或者,您可以在模板中使用%include "menuTemplate"%
...
能否提供html文件的sn-p?
@hansTheFranz menu.py
位于项目根目录的 templatetags
文件夹中。
@mateuszb templates/menu.html
只是一个基本的ul
菜单(没什么花哨的)。
@h4k1m 好的,所以您正在使用 % load project_tags % 加载 project_tags,对吧?
【参考方案1】:
我已经通过在我的base.html
模板中加载模块(即project_tags
)而不是标签(即menu
)来修复它,然后正常调用标签menu
:
原来如此
% load project_tags %
...
% menu %
代替:
% load menu %
...
% menu %
【讨论】:
以上是关于Django 中所有应用程序共享的菜单的主要内容,如果未能解决你的问题,请参考以下文章
Python / Django 应用程序:带有过滤菜单的酒单。过滤逻辑应该去哪里?前端还是后端?
Finder 共享的 macOS 应用程序要求是啥,打开菜单