Load static files for all templates in django

后端 未结 2 693
独厮守ぢ
独厮守ぢ 2021-02-07 11:56

Is there a way in django to not need the {% load static %} at the top of every template?

This question indicates you can factor out common load tags into se

2条回答
  •  醉话见心
    2021-02-07 12:28

    As of Django 1.9, you can add a builtins key to your TEMPLATES["OPTIONS"] in settings.py.

    For Django 2.1+, use:

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

    For Django 1.9 - 2.0 (this will work up until 2.2, after which it is deprecated), use:

    '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.

提交回复
热议问题