1、模板路徑配置css
1.在項目中建立templates文件夾存放模板文件html
2.修改settings.py文件python
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', ], }, }, ]
3.使用模板文件數據庫
def show_article(request): articles = {} article_list = [] for i in range(30): dt = datetime.datetime.now() - datetime.timedelta(days=random.randint(0, 100)) article_list.append((dt, "python 函數返回多個值")) article_list = sorted(article_list, key=lambda ele: ele[0]) article_list.reverse() for article in article_list: d = article[0].strftime("%Y-%m") if not articles.get(d, None): articles[d] = [] articles[d].append(article) return render(request, 'article/show-article.html', context={"articles": articles})
上述代碼中的模板路徑表示在templates目錄下存在article目錄下的show-article.html文件,通常會在templates下建立與每一個應用名相同的文件夾,用於存放該應用的模板。django
4.模板配置的兩種方式app
第一種:DIRS 定義一個目錄列表,模板引擎按列表順序搜索這些目錄以查找模板源文件,將templates放在主項目目錄下。dom
前3步使用了第一種方式,這種方式是經常使用方式。
函數
第二種:APP_DIRS告訴模板引擎是否應該進入每一個已安裝的應用中查找模板,值爲True則模板會去安裝了的app下面的templates文件夾查找模板,因此咱們也能夠在每一個app的裏面建立模板目錄templates存放模板,這種方式須要將這個app添加到setting.py文件的INSTALLED_APPS列表中。oop
2、模板變量字體
1.使用規則
語法: {{ 變量名 }};
命名由字母和數字以及下劃線組成,不能有空格和標點符號;
可使用字典、模型、方法、函數、列表,方法和函數不能帶括號;
不要和python或django關鍵字重名;
變量和查找;
2.注意的地方
若是data是一個字典,那麼訪問data.items將會訪問data這個字典的key名爲items的值,而不會訪問字典的items方法。
點在模板渲染時有特殊的含義。 變量名中點表示查找。
3、過濾器
1.語法:
{{fruits|lower}} 不帶參數的過濾器
{{fruits|cut:''}} 帶參數的過濾器(使用參數的時候,冒號和參數之間不能有任何空格,必定要緊挨着。)
{fruits|lower|capfirst} 多重過濾器
2.經常使用過濾器
3.date和time過濾器格式(這兩個過濾器過濾的值必須是datetime格式,不能是字符串)
4.使用示例
4、靜態文件配置
1.在主項目目錄下建立static文件夾
2.修改settings.py(添加STATICFILES_DIRS變量)
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]
3.使用靜態文件的方式(靜態文件包括css文件、js文件、圖片、字體文件等)
{% load static %} <link rel="stylesheet" href="{% static 'css/show-article.css' %}">
使用前須要加載,也能夠不用加載,可是必須在settingspy文件中進行配置
加載不配置:
{% load static %}
配置不加載(以下配置後就不用了加載了)
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'],
}, }, ]
引用的方式
<link rel="stylesheet" href="{% static 'css/index.css' %}" />
5、標籤
1.語法:由%}和 {% 來定義的,例如:{%tag%} {%endtag%}
2.做用:若是說模板變量至關於變量,那麼標籤就是控制結構。
3.經常使用的標籤(注:forloop.counter、forloop.counter0等是變量)
4.標籤示例:(繼承模板的標籤{% extends ''%}必須放在模板文件的最前面)
<!--if--> {% if name == "python" %} 這個是python的頁面 {% elif name == "Java" %} 這個是Java的頁面 {% else %} 這個是{{name}}的頁面 {% endif %} <!--for--> <ul> {% for title in titles %} <li>{{title}}</li> {% endfor %} </ul> <!--url:通常配合視圖的名稱來--> <!-- urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('user/', include("User.urls")), path('article/', include("Article.urls")), path('collection/', include("Collection.urls")), path('getcode/', views.send_code, name='code') ] --> <a hre="{% url 'index' %}">首頁</a> <!--with--> {% with test_name as tn %} {{tn}} {% endwith %} <!--autoescape--> 原始的:{{html}} 過濾器方式: {{ html | safe }} 標籤方式 {% autoescape off %} {{ html }} {% endautoescape %}
6、自定義標籤
1.自定義過濾器、標籤路徑配置
模板是放在主目錄下的templates文件夾中,而自定義過濾器、標籤是放在templatetags包下面。
第一步:在主目錄下建立一個名爲common的Python包
第二步:將commom這個包註冊到settings.py的INSTALLED_APP變量中
第三步:在common包中建立templatetags包
第四步:在templatetags包中建立一個extra.py用於存放自定義過濾器和標籤的模塊(注意:templatetags這個包名是固定的,裏面的模塊名是自定義的)
第五步:在extra.py中編寫自定義過濾器和模塊的代碼(注意:要遵照自定義的規則)
2.自定義過濾器
分析:過濾器過濾的對象能夠看作是過濾器的第一個參數,若是過濾器後面還要跟參數就是兩個參數,因此咱們能夠得出過濾器就是一個帶有一個或兩個參數的Python 函數
from django import template register = template.Library() # 自定義cut過濾器 # cut過濾器後面必需要跟一個參數,因此有兩個參數 @register.filter def self_cut(value, arg): if isinstance(value, (str, )): return value.replace(arg, "") else: return value # 自定義字母大寫過濾器 # 字母大寫過濾前面的值,不用再加另外的參數,因此有一個參數 @register.filter def self_upper(value): if isinstance(value, (str, )) and value.isalpha(): return value.upper() else: return value # 分析Library.filter(self, name=None, filter_func=None, **flags)參數 # name表示過濾器的名稱,若是沒有給,就默認爲函數名 # filter_func就是你編寫的函數名
3.自定義標籤
3.1自定義標籤種類:
簡單標籤:django.template.Library.simple_tag()
包含標籤:django.template.Library.inclusion_tag()
3.2分析:自定義簡單標籤能夠沒有參數,一個參數或者是使用context中存在的參數,注意若是使用context中存在的參數必須保證傳的context有這個參數
自定義簡單標籤
from django import template import datetime register = template.Library() # 參數分析 # Library.simple_tag(self, func=None, takes_context=None, name=None) # 參數分析:func:標籤函數 takes_context:是否使用context name:定製標籤名 # 自定義一個顯示當前時間的標籤 # 無參數 @register.simple_tag def now(): return datetime.datetime.now() # 自定義一個顯示當前時間的標籤,且這個標籤能夠接受格式化時間參數 # 一個參數 @register.simple_tag def now(format_string): return datetime.datetime.now().strftime(format_string) # 使用context做爲參數 # 還須要將Library.simple_tag(self, func=None, takes_context=None, name=None)中take_context設置爲True @register.simple_tag(takes_context=True) def now(context): format_string = context.get("format_string", None) if format_string: return datetime.datetime.now().strftime(format_string) else: return None
自定義包含標籤:經過將自定義包含標籤函數的返回值(字典)渲染到指定的模板中,從而使用包含標籤時,顯示渲染的模板,能夠經過查詢數據庫獲取渲染數據。
下面的代碼原本是寫在HTML頁面中的,經過context渲染,如今我把它抽出來,專門做爲一個自定義包含標籤:
<ul class="list-group"> {% for k, list in articles.items %} <li class="list-group-item list-group-item-success"><h4>{{ k }}</h4></li> <ul id="article-list"> {% for a in list %} <li class="text-info"><h5>{{ a.0 | date:"m-d" }} {{ a.1 }}</h5></li> {% endfor %} </ul> {% endfor %} </ul>
from django import template import datetime import random register = template.Library() @register.inclusion_tag(filename="include/show_article.html") def show_article(): articles = {} article_list = [] for i in range(30): dt = datetime.datetime.now() - datetime.timedelta(days=random.randint(0, 100)) article_list.append((dt, "python 函數返回多個值")) article_list = sorted(article_list, key=lambda ele: ele[0]) article_list.reverse() for article in article_list: d = article[0].strftime("%Y-%m") if not articles.get(d, None): articles[d] = [] articles[d].append(article) return {"articles": articles}
{% extends 'base/base-no-main-left.html' %} {# 使用前必須先加載static #} {% load static %} {% load extra %} {% block link %} <link rel="stylesheet" href="{% static 'css/show-article.css' %}"> {% endblock %} {% block main-left %} {% show_article %} {% endblock %}
4.自定義過濾器、標籤的使用
當自定義過濾器和標籤編寫好後,就可使用了;在模板中使用,必需要加載自定義過濾器、標籤所在的模塊,上述標籤、過濾器是在extra.py文件中,且路徑配置無誤,
那麼就能夠加載使用了
{% extends 'base/base-no-main-left.html' %} {# 使用前必須先加載static #} {% load static %} {% load extra %} {% block link %} <link rel="stylesheet" href="{% static 'css/show-article.css' %}"> {% endblock %} {% block main-left %} {% show_article %} {% endblock %}