简体   繁体   English

为django中的所有模板加载静态文件

[英]Load static files for all templates in django

Is there a way in django to not need the {% load static %} at the top of every template? django 中有没有办法不需要每个模板顶部的{% load static %}

This question indicates you can factor out common load tags into settings, but doesn't give the particulars you need in this case. 这个问题表明您可以将常见的负载标签分解到设置中,但在这种情况下没有提供您需要的详细信息。

As of Django 1.9, you can add a builtins key to your TEMPLATES["OPTIONS"] in settings.py .从 Django 1.9 开始,您可以向settings.py TEMPLATES["OPTIONS"]添加builtins键。

For Django 2.1+, use:对于 Django 2.1+,使用:

'builtins': ['django.templatetags.static']

For Django 1.9 - 2.0 (this will work up until 2.2, after which it is deprecated), use:对于 Django 1.9 - 2.0(这将一直工作到 2.2,之后它被弃用),使用:

'builtins': ['django.contrib.staticfiles.templatetags.staticfiles']

For example, the whole template setting might look like this:例如,整个模板设置可能如下所示:

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',
            ],
            'builtins': ['django.templatetags.static'],
        },
    },
]

Thanks to @ZachPlachue for the Django 3 update.感谢@ZachPlachue为 Django 3 更新。

The previous answer's method is deprecated as of Django 3.0.从 Django 3.0 开始,不推荐使用上一个答案的方法。 (see : https://docs.djangoproject.com/en/3.0/releases/3.0/#features-removed-in-3-0 ) (见: https : //docs.djangoproject.com/en/3.0/releases/3.0/#features-removed-in-3-0

Now you'd need to add the following to your template settings:现在您需要将以下内容添加到您的模板设置中:

'builtins': ['django.templatetags.static']

This is the updated templates setting:这是更新后的模板设置:

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',
            ],
            'builtins': [
                'django.templatetags.static',
            ],
        },
    },
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM