Django DTL模板语法中的循环
生活随笔
收集整理的這篇文章主要介紹了
Django DTL模板语法中的循环
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 from django.shortcuts import render
2
3 def index(request):
4 context={
5 'books':[
6 '5年高考3年模擬',
7 '家豬養殖與配種',
8 'Python 3 面向對象編程',
9 'MySQL數據庫從刪庫到跑路'
10 ],
11 'person':{
12 'username':'randomlee',
13 'age':'25',
14 'height':'180'
15 },
16 'book2s':[
17 {
18 'name':'5年高考3年模擬',
19 'author':'黃岡中學',
20 'price':'32'
21 },
22 {
23 'name':'家豬養殖與配種',
24 'author':'不知道',
25 'price':'40'
26 },{
27 'name':'Python 3 面向對象編程',
28 'author':'a',
29 'price':'22'
30 },{
31 'name':'MySQL數據庫從刪庫到跑路',
32 'author':'abc',
33 'price':'33'
34 }
35 ],
36 'comments':[
37 ' 文章的評論內容'
38 ]
39 }
40 return render(request,'index.html',context) views.py 1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 <style>
7 body {
8 text-align: center;
9 background: pink;
10 {#line-height: 100px;#}
11 }
12 td{
13 border: 1px solid;
14 padding: 10px;
15
16 }
17 table{
18 text-align: center;
19 }
20 </style>
21
22 </head>
23 <body>
24 <ul>
25
26 {% for book in books reversed %}
27 <li>{{ book }}</li>
28 {% endfor %}
29 </ul>
30 <ul>
31 {% for v in person.values %}
32 <li>{{ v }}</li>
33 {% endfor %}
34 {% for k in person.keys %}
35 <li>{{ k }}</li>
36 {% endfor %}
37 {% for k,v in person.items %}
38 <li>{{ k }}/{{ v }}</li>
39 {% endfor %}
40
41 </ul>
42
43 <table>
44 <thead>
45 <tr>
46 <td>從1開始序號</td>
47 <td>從0開始序號</td>
48 <td>反轉序號最后一位是1</td>
49 <td>反轉序號最后一位是0</td>
50 <td>書名</td>
51 <td>作者</td>
52 <td>價格</td>
53 </tr>
54 </thead>
55 <tbody>
56
57 {% for book2 in book2s %}
58 {% if forloop.first %}
59 {# 是否是遍歷的第一行 #}
60 <tr style="background: red" >
61 {% elif forloop.last %}
62 {# 是否遍歷的最后一行#}
63 <tr style="background: blue">
64 {% else %}
65 <tr>
66 {% endif %}
67 <td>{{ forloop.counter }}</td>
68 <td>{{ forloop.counter0 }}</td>
69 <td>{{ forloop.revcounter }}</td>
70 <td>{{ forloop.revcounter0 }}</td>
71 <td>{{ book2.name }}</td>
72 <td>{{ book2.author }}</td>
73 <td>{{ book2.price }}</td>
74 </tr>
75 {% endfor %}
76
77
78 </tbody>
79 </table>
80
81 <ul>
82 {% for comment in comments %}
83 <li>{{ comment }}</li>
84 {% empty %}
85 <li>沒有任何評論</li>
86 {% endfor %}
87
88 </ul>
89
90 </body>
91 </html> index.html
template_for_demo.zip?
轉載于:https://www.cnblogs.com/randomlee/p/10291487.html
總結
以上是生活随笔為你收集整理的Django DTL模板语法中的循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Luogu4606 SDOI2018 战
- 下一篇: Google Capture The F