天天看點

Django2.2 學習筆記 (13)_{% static %}标簽的使用

在模版中使用load标簽加載static标簽

比如要加載在項目的static檔案夾下的style.css的檔案。那麼示例代碼如下:

{% load static %}

<link rel="stylesheet" href="{% static 'style.css' %}" target="_blank" rel="external nofollow" >
           

注意1: {% load static %}需要放在html的頭部位置(至少在使用static标簽的上面),一般都是放在html的最上面

注意2:如果{% extend %}标簽和{% load static %}同時存在,{% extend %}需要放在最上面,然後再放{% load static %}等标簽

注意3:如果不想每次在模版中加載靜态檔案都使用load加載static标簽,那麼可以在settings.py中的TEMPLATES/OPTIONS添加'builtins':['django.templatetags.static'],這樣以後在模版中就可以直接使用static标簽,而不用手動的load了。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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'
            ],
        },
    },
]
           

注意4:如果有一些靜态檔案是不和任何app挂鈎的。即不再任何一個app的目錄下。那麼可以在settings.py中添加STATICFILES_DIRS,以後DTL就會在這個清單的路徑中查找靜态檔案。例如我們在manage.py的同級目錄下建立一個static的檔案夾。然後在settings.py:中添加STATICFILES_DIRS

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
           

end