由來
因爲使用 django.http.HttpResponse() 來輸出 “Hello World!”。該方式將數據與視圖混合在一起,不符合 Django 的 MVC 思想,所以有了Django 模板的應用,用於分離文檔的表現形式和內容。
語法
- 雙括號
hello.html 文件代碼:
<h1>{{ hello }}</h1>
view.py 文件代碼:
from django.shortcuts import render
def hello(request):
context = {}
context['hello'] = 'Hello World!'
return render(request, 'hello.html', context)# context 字典中元素的鍵值 "hello" 對應了模板中的變量 "{{ hello }}"。
# 或
def hello(request):
hello= 'Hello World!'
return render(request, 'hello.html', {”hello“:hello})
- if/else 標籤
//基本語法格式如下:
{% if condition %}
... display
{% endif %}
//或者:
{% if condition1 %}
... display 1
{% elif condition2 %}
... display 2
{% else %}
... display 3
{% endif %}
//{% if %} 標籤接受 and , or 或者 not 關鍵字來對多個變量做判斷 ,或者對變量取反( not )
- for 標籤
//{% for %} 允許我們在一個序列上迭代。
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
- ifequal/ifnotequal 標籤
//{% ifequal %} 標籤比較兩個值,當他們相等時,顯示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}
- 註釋標籤
Django 註釋使用 {# #}。 - 過濾器
模板過濾器可以在變量被顯示前修改它,過濾器使用管道字符
{{ my_list|first|upper }} - 模板繼承
所有的 {% block %} 標籤告訴模板引擎,子模板可以重載這些部分。
{% block mainbody %}
<p>original</p>
{% endblock %}
{% block mainbody %}
<p>繼承了上面的文件</p>
{% endblock %}
注意
需要向Django說明模板文件的路徑,修改settings.py,修改 TEMPLATES 中的 DIRS 爲 [BASE_DIR+"/templates",]