VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 【django入门】 03 模板语法

变量值从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>
  • 效果 image

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>
  • 效果 image
  • 附加知识:django html条件语句

 
{% if strHtml1 == "abc" %}
 
……
 
{% elif strHtml1 == "def" %}
 
……
 
{% else %}
 
……
 
{% endif %}

总结

  • {{ }}、{% %} 这些替换字符串,会被django在渲染html时替换,因而不会被终端用户看见
  • mosh(一个老外)的经验,尽量在views.py里写条件语句,写在html里会造成代码界面混乱

来源:BV1NL41157 武沛齐《2022 B站最详细django3教程(django从入门到实践)》P10


相关教程