Django2.2 学习笔记 (13)_{% static %}标签的使用

在模版中使用load标签加载static标签

比如要加载在项目的static文件夹下的style.css的文件。那么示例代码如下:

{% load static %}

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

注意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

发布了18 篇原创文章 · 获赞 0 · 访问量 564

猜你喜欢

转载自blog.csdn.net/zhsworld/article/details/104036472