(12)模板语言-with

with的用处

当一个变量特别特别长,可以用with给这个变量重命名

views.py

from django.shortcuts import render,HttpResponse

def index(request):
   #可以看到这里传入的一个变量中的key后面跟了一个列表
dic = {'hobby':['p','sl']}
return render(request,'index.html',{'dic':dic})

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>我是首页</h1>
{{ dic }}

{#取出变量dic的对应key名中的索引位置为1的值 #}
<p>{{ dic.hobby.1 }}</p>

{#如果一个变量特别长,每次取值很麻烦要打很长的代码,用with可以将这个变量重命名,以后使用直接调用这个变量名就可以 #}
{% with dic.hobby.1 as aaa %}
<p>{{ aaa }}</p>
{% endwith %}
</body>
</html>

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'index/', views.index)
]

猜你喜欢

转载自www.cnblogs.com/shizhengquan/p/10510633.html