django template question (accessing a list)

前端 未结 4 1534
半阙折子戏
半阙折子戏 2021-01-07 04:14

I am writing a template for my first django website.

I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which h

4条回答
  •  心在旅途
    2021-01-07 04:37

    In short, Django doesn't do what you want.

    The for loop has a number of useful properties within a loop.

    forloop.counter     The current iteration of the loop (1-indexed)
    forloop.counter0    The current iteration of the loop (0-indexed)
    forloop.revcounter  The number of iterations from the end of the loop (1-indexed)
    forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
    forloop.first       True if this is the first time through the loop
    forloop.last        True if this is the last time through the loop
    forloop.parentloop  For nested loops, this is the loop "above" the current one
    

    You could probably use forloop.counter0 to get the zero-based indexes you want; unfortunately, the Django template language doesn't support variable array indexes (You can do {{ foo.5 }}, but you can't do {{ foo.{{bar}} }}).

    What I usually do is to try and arrange the data in the view to make it easier to present in the template. As an example, for you could create an array in your view composed of dictionaries so that all you have to do is loop through the array and pull exactly what you need out of the individual dictionaries. For really complicated things, I've gone so far as to create a DataRow object that would correctly format the data for a particular row in a table.

提交回复
热议问题