Django's templates don't support indirect variable lookup like this. You
need to either write a template filter to do the lookup based on the
argument you pass in (forloop.counter), or find one on the internet --
it might well already exist, but I have no idea because I arrange my
template output to never require it.
Alternatively restructure your data (in your view) so that you can
iterate over the things you need all at once. For example, if list1 and
list2 are the objects you're iterating over, change the view to pass
zip(list1, list2) into the template and then iterate over the combined
result with:
{% for val1,val2 in combined_result %}
...
{% endfor %}
Regards,
Malcolm
Then you are free to write a template filter to do what you like. It's
probably about three lines long.
> 2.And also It would be better if we can have tag / filter which
> directly gives us an element from the list by taking position as its
> input.
Fortunately, Django allows you to write one. In fact, writing filters to
do things like this is encouraged. It's a feature.
> such as.......... {{ list|forloop.counter }}. May be in django
> next release.........
Pretty much no chance, I suspect. Indirect variable lookups are pretty
much "programming in templates". The idea, if you're wanting to use the
templates without additions, is to structure the data in the view
function so that the template just dumps data into holes in the
structure it provides. If you're having to compute which piece of data
to get based on some other piece of data, then you can do that in this
great language we've provided called "Python".
That might sound arbitrary and I'm partially writing tongue-in-cheek,
but the principle is very sound. Once you start having arbitrary
language constructs in templates, the line between what logic to put in
the template and what to keep in the Python function that produces the
data becomes blurry and very inconsistent. Django's default setup
strives to keep that line pretty clean.
Some people don't like where the line is, which is fine. There's no
satisfying everybody and it's one of the great reasons to permit and
encourage custom template tags and filters and sharing thereof. The
ability to make extensions is a first-class feature of Django's
templates, not some accidental side-effect. And if that still doesn't
satisfy you, you can also use pretty much any other templating language
you like (even PHP) to render the results. I'd still encourage thinking
about how to keep that kind of logic out of the template, having
maintained some pretty large collections of templates in Turing-complete
templating languages that steadily became harder and harder to control,
but it's up to you which trade-offs you want to make as far as balancing
"the now" and "the future".
Regards,
Malcolm