默认情况下,为所有视图加载Django模板标记库
我有一个小的与排版相关的templatetag库,我几乎在每一页上都使用它。现在,我需要使用为每个模板加载它默认情况下,为所有视图加载Django模板标记库,django,django-templates,Django,Django Templates,我有一个小的与排版相关的templatetag库,我几乎在每一页上都使用它。现在,我需要使用为每个模板加载它 {% load nbsp %} 是否有一种方法可以一次“全局”加载所有视图和模板?将load标记放入基本模板不起作用。在django.template.loader中有一个add\u to\u builtins方法。只需将templatetags模块的名称传递给它(作为字符串) 现在,mytagslib在任何模板中都可以自动使用。在django 1.7中,只需从django.templ
{% load nbsp %}
是否有一种方法可以一次“全局”加载所有视图和模板?将load标记放入基本模板不起作用。在
django.template.loader
中有一个add\u to\u builtins
方法。只需将templatetags模块的名称传递给它(作为字符串)
现在,mytagslib在任何模板中都可以自动使用。在django 1.7中,只需从django.template.base导入添加到内置的
,它将随django 1.9版本而更改
从1.9开始,正确的方法是在选项
的内置
键下配置模板标签和过滤器-参见下面的示例:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'builtins': ['myapp.builtins'],
},
},
]
详情:
在Django 1.9中,有一个库
标签字典和模板标记模块的点式Python路径,用于向模板引擎注册。这可用于添加新库或为现有库提供替代标签
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
'libraries': { # Adding this section should work around the issue.
'custom_tags' : 'myapp.templatetags.custom_tags',#to add new tags module.
'i18n' : 'myapp.templatetags.custom_i18n', #to replace exsiting tags modile
},
},
},
]
请注意,虽然你可以这样做,但很可能在某个时候你会后悔(我做了,后悔了)。它使您的模板不可移植到任何其他未将\添加到\内置项的项目,并且它可以中断呈现这些模板的测试(除非您确保测试运行程序也运行了将\添加到\内置项)。总而言之,它让事情变得更加脆弱,只是为了获得一点点便利。更不用说,任何新开发人员都会因为你使用了标准库中不存在的标记而感到困惑,直到他们问你(如果你还在的话)或偶然发现它为止。:)记住,显式比隐式好。我们能用它覆盖XSS错误的默认firstof和cycle标记吗?实际上,我现在正在使用{%filter force\u escape%}{%firstof var1 var2 var3“fallback value”%}{%endfilter%}
解决方案。在下面给出的新导入路径下,这种方法似乎仍然有效:从django.template.base导入将\u添加到\u内置为什么要进行下推?这救了我一天,因为被接受的答案已经过时了!Django 1.7中的导入路径已更改。谢谢你!这应该是评论还是编辑?它本身没有意义。到目前为止(Django 1.9),这应该是公认的答案。内置:['Django.templatetags.i18n'],
哦,是的。我不知道如何将此选项链接到我的实际模板标记文件,以及是否需要向模板标记文件添加任何内容以将其注册为内置文件。没有关于django的文档。任何人都可以编辑这个答案来提供完整的细节吗。?谢谢
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
'libraries': { # Adding this section should work around the issue.
'custom_tags' : 'myapp.templatetags.custom_tags',#to add new tags module.
'i18n' : 'myapp.templatetags.custom_i18n', #to replace exsiting tags modile
},
},
},
]