Django模板遍歷字典的方法

2021-08-20 02:04:17 字數 1782 閱讀 8361

** liqi328163 的 《django模板遍歷字典的方法》

python**  

"color: #000000;"> 

使用python + django做web開發時,有時需要在view中傳遞乙個字典給模板(template),如何在模板中遍歷字典呢?

下面介紹兩種方法:

views.py**如下:

python**  

"color: #000000;">def forward(request):  

dicts =   

return render_to_response("index.html",,context_instance = requestcontext(request))  

1.第一種遍歷方法:

index.html**如下:

python**  

"color: #000000;">............

python**  

"color: #000000;">  

class="">              }}

}python**  

"color: #000000;">............

這種方法遍歷字典,簡單明瞭,但由於字典是無序的,  不能滿足特定的要求,如:首先輸出key2,在輸出key1,key3。要做到這點就需要使用第二種方法。

2. 第二種使用自定義過濾器

1):首先自定義過濾器:

django

polls/  

models.py  

templatetags/

views.py

新增兩個檔案到templatetags包(即該目錄下),乙個__init__.py檔案(來告訴

python

這是乙個包含python**的模組)和乙個包含你的自定義的標籤/過濾器定義的檔案,後者的檔名是你將在後面用來載入標籤的名字,例如,如果你的自定義標籤或者過濾器在乙個叫myfilter.py檔案裡,你可以在模板裡做下面的事情:

myfilter.py**如下:

python**  

"color: #000000;">from django import template  

register = template.library()  

defkey(d,key_name):      

value = 0

try:          

value = d[key_name]      

except keyerror:          

value = 0

return value

python**  

"color: #000000;">register.filter('key',key)

模板index.html**如下:

python**  

"color: #000000;">

"color: #000000;">

python**  

"color: #000000;">.........

python**  

"color: #000000;">class="altrow">           

1              

key2

}  2

key1

}  class="altrow">             

3              

key3} 

Django中列表和字典的遍歷

templates 中的 runoob.html中,可以用 索引下標取出對應的元素。from django.shortcuts import render def runoob request views list 菜鳥教程1 菜鳥教程2 菜鳥教程3 return render request,ru...

Django 簡單模板遍歷渲染

簡單路由 urlpatterns path admin admin.site.urls path index views.index path list views.list 加單控制器 user list for i in range 10 temp deflist request print u...

遍歷字典 十三 Python字典三種遍歷方法

python字典是最基本的資料結構之一,在python中使用非常頻繁,所以對python字典的遍歷非常重要。下面介紹常用的幾種字典遍歷方法。d1 根據key遍歷字典獲取值for key in d1.keys print f key value d1 遍歷value值for value in d1.v...