python + django 搭建網頁(嘗試3):模板
阿新 • • 發佈:2022-01-16
參考:
[1] https://www.runoob.com/django/django-template.html
1. 檢視模板
設定檢視模板是為了使“資料與檢視分離”。
1.1 設定路徑,包括 templates 資料夾
settings.py 中
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 修改位置
1.2 編輯模板
templates/runoob.html 中:
<h1>{{ hello }}</h1>
1.3 設定動作函式
views.py 中:
def runoob(request): context = {} context['hello'] = 'Hello World!' return render(request, 'runoob.html', context)
1.4 關聯 url
urls.py 中:
urlpatterns = [
path('runoob/', views.runoob),
]
2. Ref. [1] 剩餘內容中有意思的點
Ref. [1] 中還有很多關於模板的內容,但大多數我估計用不著,所以只摘錄一點點似乎用得著的:
2.1 date
動作函式:
def runoob(request):
import datetime
now =datetime.datetime.now()
return render(request, "runoob.html", {"time": now})
runoob.html:
{{ time|date:"Y-m-d" }}
效果:
2020-05-16
2.2 safe
Django 會自動對 views.py 傳到 HTML 檔案中的標籤語法進行轉義,令超連結語義失效。加 safe 過濾器是告訴 Django 該資料是安全的,不必對其進行轉義,可以讓該資料語義生效。
例如,views.py 中:
def runoob(request): views_str = "<a href='https://www.runoob.com/'>點選跳轉</a>" return render(request, "runoob.html", {"views_str": views_str})
runoob.html中:
{{ views_str|safe }} # 加這個 safe 才會有超連結
2.3 條件判斷
{% if condition1 %}
... display 1
{% elif condition2 %}
... display 2
{% else %}
... display 3
{% endif %}
可以巢狀使用。例如 views.py 中:
def runoob(request):
views_num = 88
return render(request, "runoob.html", {"num": views_num})
runoob.html 中:
{%if num > 90 and num <= 100 %}
優秀
{% elif num > 60 and num <= 90 %}
合格
{% else %}
一邊玩去~
{% endif %}
2.4 迴圈語句
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
例如:views.py 中:
def runoob(request):
views_list = ["菜鳥教程","菜鳥教程1","菜鳥教程2","菜鳥教程3",]
return render(request, "runoob.html", {"views_list": views_list})
runoob.html 中:
{% for i in views_list %}
{{ i }}
{% endfor %}
感覺如果能學一下 html 語言,會比較有幫助。
2.5 {% empty %}:迴圈為空時執行
例如:
{% for i in listvar %}
{{ forloop.counter0 }}
{% empty %}
空空如也~
{% endfor %}