第二十二节 with标签使用详解

类似于python中的变量赋值

views.py 代码

1 from django.shortcuts import render,HttpResponse,redirect,reverse
2 
3 def index(request):
4     context = {
5         'books':['林花谢了春红', '太匆匆', '无奈朝来寒雨', '晚来风', '胭脂泪', '相留醉', '几时重', '自是人生长恨水长东'],
6     }
7     return render(request, 'index.html', context=context)

index.html 代码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>模板渲染</title>
 6 </head>
 7 <body>
 8     <!-- 第一种写法  -->
 9     {% with a=books.0 %}
10     <!-- 等号两边不能有空格,定义的变量只能在with块中使用 -->
11         <p>{{ a }}</p>
12     {% endwith %}
13     <br>
14     <br>
15     <!-- 第二种写法  -->
16     {% with books.1 as b %}
17     <!-- 等号两边不能有空格,定义的变量只能在with块中使用 -->
18         <p>{{ b }}</p>
19     {% endwith %}
20 
21 </body>
22 </html>

猜你喜欢

转载自www.cnblogs.com/kogmaw/p/12445775.html