Django(3)---語法
阿新 • • 發佈:2018-11-08
具體參考Django官方文件
首先要在setting.py中配置模板路徑
TEMPLATES = [{ 'DIRS': [os.path.join(BASE_DIR,'templates')], }]
建立一個templates資料夾(推薦app的放在各自的資料夾下)
應用下的views.py中配置引數
def index(request): #rendeer:渲染 #模板:html檔案 #template_name;指定要渲染的模板的名稱 return render(request, template_name='temrender/index.html', )
注意:引用模板可以在templates下新建立資料夾,將模板放入新資料夾裡面,這樣可以避免模板引用錯誤
模板內的語法
views.py的return中配置
return render(request,template_name='temrender/index.html',context={ 'name':'張三', 'books':['html','js','css','python',100], 'date':datetime.datetime.now(), 'people':p, 'dict':{'username':'hh','password':'1234'}, 'input':'<h1>這是一個h1標籤</h1>' })
- {{ }}:作用就是用於載入一個變數的值
- {% %}:作用就是用來寫for迴圈.if判斷等條件語句的語法
<h1>{{ name }}</h1>
- 通過索引取值
<h1>{{ books.0 }}--{{ books.1 }}--{{ books.2 }}--{{ books.3 }}--{{ books.4 }}</h1>
- 通過for迴圈遍歷
{% for book in books %} <p>{{ book }}</p> {% endfor %}
- 判斷
#判斷大小
{% if people.age < 18 %}
<p>未成年人</p>
{% elif people.age < 30 %}
<p>中年人</p>
{% else %}
<p>老年人</p>
{% endif %}
#判斷是否存在
{% if name %}
<p>name變數是存在的</p>
{% else %}
<p>name變數不存在</p>
{% endif %}
- 通過鍵取值
<p>{{ dict.username }}-{{ dict.password }}</p>
- 遍歷字典取值
{% for key,value in dict.items %}
<p>{{ key }}-{{ value }}</p>
{% endfor %}
列表的其他兩種遍歷方式
{% for book in books %}
{# forloop.counter:獲取迴圈的計數 #}
<p>{{ forloop.counter }}:{{ book }}</p>{# counter:計數從1開始;12345 #}
<p>{{ forloop.counter0 }}:{{ book }}</p> {# counter0:計數從0開始;012345 #}
<p>{{ forloop.revcounter }}:{{ book }}</p> {# revcounter:倒著從計數從7開始;7654 #}
<p>{{ forloop.revcounter0 }}:{{ book }}</p> {# revcounter0:倒著從計數從6開始;654 #}
{% endfor %}
- 過濾器:對{{變數}}的值進行處理
sale, upper, lower, first, lase, cut
<p>{{ date |date:'Y-m-d h:i:s' }}</p>
<p>{{ dict.username | upper |lower |capfirst }}</p>
<p>{{ input |safe }}</p>
- {% autoescape off %}:off就是關閉自動轉義,通過這個內建標籤,可以將(字串中的h1標籤)轉化成(html中h1標籤 )
{% autoescape off %}
<p> {{ input }}</p>
{% endautoescape %}