變數值從views.py傳入html
- 基本語法
{{ abc }}
變數abc外,用雙大括號包裹{% for item in abc %}
陳述句外,用大括號+百分號包裹
1. 傳遞字串
- views.py中,def內
注意views.py外部變數(str1)不需要引號包裹,*.html內部變數(strHtml)需要引號包裹
def index(request):
str1 = "someValue"
return render(request, 'index.html', {"strHtml1": str})
- index.html中,<body>內
<div>{{ strHtml1 }}<div>
2. 傳遞串列
- views.py中,def內
def index(request):
list1 = ["someValue1", "someValue2","someValue3"]
return render(request, 'index.html', {"listHtml1": list1})
- index.html中,<body>內
<div>
{% for item in listHtml1 %}
{{ item }}
{% endfor %}
<div>{{ listHtml1.0 }}</div>
<div>{{ listHtml1.1 }}</div>
<div>{{ listHtml1.2 }}</div>
</div>
- 效果

3. 傳遞字典
- views.py中,def內
def index(request):
dict1 = {"key1": "someValue1", "key2": "someValue2", "key3": "someValue3"}
return render(request, 'index.html', {"dictHtml1": dict1})
- index.html中,<body>內
<div>
{% for k in dictHtml1.keys %}
{{ k }}
{% endfor %} <br><br><br>
{% for v in dictHtml1.values %}
{{ v }}
{% endfor %} <br><br><br>
{% for k,v in dictHtml1.items %}
<div>{{ k }}={{ v }}</div>
{% endfor %} <br><br><br>
<div>{{ dictHtml1.key1 }}</div>
<div>{{ dictHtml1.key2 }}</div>
<div>{{ dictHtml1.key3 }}</div>
</div>
- 效果
4. 傳遞串列中的字典
- views.py中,def內
def index(request):
list_info = [
{"name": "zhang", "age": 14, "province": "hunan"},
{"name": "li", "age": 15, "province": "tianjin"},
{"name": "tian", "age": 16, "province": "shanghai"},
]
return render(request, "index.html", {"listHtml1": list_info})
- index.html中,<body>內
<div>{{ listHtml1.1 }}</div>
<div>{{ listHtml1.1.name }}</div>
<div>{{ listHtml1.1.age }}</div><br>
{% for item in listHtml1 %}
<div>{{ item.name }} : {{ item.age }} : {{ item.province }}</div>
{% endfor %} <br>
<ul>
{% for item in listHtml1 %}
<li> {{ item.name }} : {{ item.age }} : {{ item.province }} </li>
{% endfor %}
</ul> <br>
- 效果

- 附加知識:django html條件陳述句
{% if strHtml1 == "abc" %}
……
{% elif strHtml1 == "def" %}
……
{% else %}
……
{% endif %}
總結
- {{ }}、{% %} 這些替換字串,會被django在渲染html時替換,因而不會被終端用戶看見
- mosh(一個老外)的經驗,盡量在views.py里寫條件陳述句,寫在html里會造成代碼界面混亂
來源:BV1NL41157 武沛齊《2022 B站最詳細django3教程(django從入門到實踐)》P10
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/423453.html
標籤:其他
