代码之家  ›  专栏  ›  技术社区  ›  Tomas Andrle

默认情况下,为所有视图加载Django模板标记库

  •  47
  • Tomas Andrle  · 技术社区  · 15 年前

    我有一个小的与排版相关的templatetag库,我几乎在每一页上都使用它。现在,我需要使用为每个模板加载它

    {% load nbsp %}
    

    是否有一种方法可以一次“全局”加载所有视图和模板?将load标记放入基础模板不起作用。

    4 回复  |  直到 15 年前
        1
  •  74
  •   Daniel Roseman    15 年前

    有一个 add_to_builtins 方法 django.template.loader . 只需将templatetags模块的名称传递给它(作为字符串)。

    from django.template.loader import add_to_builtins
    
    add_to_builtins('myapp.templatetags.mytagslib')
    

    现在 mytagslib 在任何模板中都自动可用。

        2
  •  35
  •   pbajsarowicz    9 年前

    它将随着Django 1.9的发布而改变。

    builtins 钥匙 OPTIONS -请参见下面的示例:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'builtins': ['myapp.builtins'],
            },
        },
    ]
    

    细节: https://docs.djangoproject.com/en/dev/releases/1.9/#django-template-base-add-to-builtins-is-removed

        3
  •  28
  •   AMIC MING Pak    10 年前

    在django 1.7中,只需替换 from django.template.base import add_to_builtins

        4
  •  6
  •   kartheek    7 年前

    在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
                },
            },
        },
    ]