How to access list using variable indexes in Django templates?

前端 未结 2 425
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 01:55

Say, I have two lists of objects, foo and bar. In a Django template, while looping through foo, there\'s a counter that keeps track of

2条回答
  •  有刺的猬
    2020-12-11 02:40

    You are correct that Django templates do not directly allow this, and it's because Django tries to force you to put pretty much all your presentation logic in your views. Your best option is to make a list of dicts in your context in your view, so you can iterate of that and access the members by name. Or:

    • zip your lists together instead of making them a dict and access them using {% for fooItem, barItem in zippedList %}.
    • use a less limiting templating language, like Jinja2
    • use a custom template filter, as suggested by Yuji Tomita

提交回复
热议问题