django模板語言
一、{{}}
獲取render字典
如views.py
def index(request):
return render(request, 'index.html', {'hello': 'hello blog'})
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>Hello blog</h1>
{{ hello }}
</body>
</html>
二、模板for循環
views.py
def index(request):
TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"]
return render(request, 'index.html', {'TutorialList': TutorialList})
templates/index.html
<h1>模板for循環</h1>
{% for aa in TutorialList %}
{{ aa }}
{% endfor %}
三、顯示字典中的內容
views.py
def index(request):
info_dict = {'site': u'自強學堂', 'content': u'各種IT技術教程'}
return render(request, 'index.html', {'info_dict': info_dict})
templates/index.html
<h1>顯示字典內容</h1>
站點:{{ info_dict.site }}內容:{{ info_dict.content }}
模板還可以這樣遍歷字典:
{% for key, value in info_dict.items %}
{{ key }}: {{ value }}
{% endfor %}
四、模板匯中顯示當前網址,當前用戶等
獲取當前用戶
{{ request.user }}
用戶名{{ request.user.username }}
獲取當前網址
{{ request.path }}
獲取當前GET參數
{{ request.GET.urlencode }}