Tom*_*rle 49 django django-templates
我有一个小的排版相关的模板标签库,几乎每个页面都使用它.现在我需要为每个模板加载它
{% load nbsp %}
Run Code Online (Sandbox Code Playgroud)
有没有办法一次性"全局"加载所有视图和模板?将加载标记放入基本模板不起作用.
Dan*_*man 71
有一种add_to_builtins方法django.template.loader.只需传递templatetags模块的名称(作为字符串).
from django.template.loader import add_to_builtins
add_to_builtins('myapp.templatetags.mytagslib')
Run Code Online (Sandbox Code Playgroud)
现在mytagslib可以在任何模板中自动使用.
pba*_*icz 31
它将随着Django 1.9的发布而改变.
从1.9开始,正确的方法是在builtins键下配置模板标签和过滤器OPTIONS- 请参阅下面的示例:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'builtins': ['myapp.builtins'],
},
},
]
Run Code Online (Sandbox Code Playgroud)
详细信息:https: //docs.djangoproject.com/en/dev/releases/1.9/#django-template-base-add-to-builtins-is-removed
bsa*_*sao 27
在django 1.7中只需更换 from django.template.base import add_to_builtins
在Django 1.9中,有一个libraries标签字典和模板标签模块的点缀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
},
},
},
]
Run Code Online (Sandbox Code Playgroud)