django學習筆記之forloop

在學習django時候,看到djangobook中關於forloop知識詳解中,有這麼一句話"在一個 {% for %} 塊中,已存在的變量會被移除,以避免 forloop 變量被覆蓋",這到底是什麼含義呢?下面我們來通過實例說明他的含義:

python manager.py shell
>>>
>>>from django.template import Template, Context
>>>t = Template("""
       {% for item in items %}
          {{ forloop }}
       {% endfor %}
       """)
>>>c = Context({'items': [item for item in range(10)], 'forloop': 'test'})
>>>print t.render(c)

wKioL1PLEAPxScErAAdzoa68LNo685.jpg

這裏我們故意在Context裏面設置一個forloop字典key,然後在模板裏面放一個forloop變量來"引用"傳遞過來的值,但是結果確不是我們想要的......

>>>t = Template("""
       {% for item in items %}
          {{ forloop.parentloop }}
       {% endfor %}
       """)
>>>c = Context({'items': [item for item in range(10)], 'forloop': 'test'})
>>>print t.render(c)

wKiom1PLEIHQsFfQAACtdt2mc0o342.jpg

這個結果就是我們想要的嘛


#########################################################################

結論: 

  1. 家裏人總比外來人要親嘛!

  2. " 局部變量權利大於全局變量"

  3. ......

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章