变量值从views.py传入html
1. 传递字符串
-
views.py中,def内
注意views.py外部变量(str1)不需要引号包裹,*.html内部变量(strHtml)需要引号包裹
|
def index(request): |
|
str1 = "someValue" |
|
return render(request, 'index.html', {"strHtml1": str}) |
2. 传递列表
|
def index(request): |
|
list1 = ["someValue1", "someValue2","someValue3"] |
|
return render(request, 'index.html', {"listHtml1": list1}) |
|
<div> |
|
{% for item in listHtml1 %} |
|
{{ item }} |
|
{% endfor %} |
|
|
|
<div>{{ listHtml1.0 }}</div> |
|
<div>{{ listHtml1.1 }}</div> |
|
<div>{{ listHtml1.2 }}</div> |
|
</div> |
-
效果
3. 传递字典
|
def index(request): |
|
dict1 = {"key1": "someValue1", "key2": "someValue2", "key3": "someValue3"} |
|
return render(request, 'index.html', {"dictHtml1": dict1}) |
|
<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. 传递列表中的字典
|
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}) |
|
<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> |
-
效果
|
{% if strHtml1 == "abc" %} |
|
…… |
|
{% elif strHtml1 == "def" %} |
|
…… |
|
{% else %} |
|
…… |
|
{% endif %} |
总结
-
{{ }}、{% %} 这些替换字符串,会被django在渲染html时替换,因而不会被终端用户看见
-
mosh(一个老外)的经验,尽量在views.py里写条件语句,写在html里会造成代码界面混乱
来源:BV1NL41157 武沛齐《2022 B站最详细django3教程(django从入门到实践)》P10