On Wednesday, March 21, 2012 8:47:23 AM UTC-4, larry....@gmail.com wrote:
>
> This is probably a stupid newbie question ....
>
> I want to access a column of data in a row using forloop.counter, but
> I cannot get it to work.
>
> In my test code, if I display {{ forloop.counter }} I get 2
> If I display {{ headers.0.2 }} I get ToolType
> But if I display {{ headers.0.forloop.counter }} I get nothing
>
> What is the proper syntax for this?
>

the forloop.counter and friends will simply give you information about the 
iteration, it won't give you any information about the data in the queryset 
(I'm assuming this is what you mean when you say column).

Here are the docs 
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for

 If you want to access the column of data, assuming it's referenced from a 
model, just the attribute of that model. If you passed in a list to the 
template, you just use the django "dot" look-up syntax.

Docs here: https://docs.djangoproject.com/en/dev/ref/templates/api/#render

So, let's say your list looks like a = [1,2,3,4] and in your context it 
looks like c ={'a':a}

if you want to reference the second "column" (index really) you would just 
do {{ a.1 }}, this will render the number "2".

You would use forloop.counter for something like, let's say we passed in 
hundreds of such lists. And, for whatever reason, once we reach the 100th 
iteration, we want the loop to end.

Then we would do this:

{% for list in list_of_lists %}
  {{ list.1 }}
{% if forloop.counter == 100 %}
    {% endfor %}
{% endif %}
{% if forloop. last %} 
    {% endfor %}
{% endif %} 

The last if / endif is not necessary, but I wanted to show some control 
flow using the forloop context. In fact, I wouldn't do this at all at the 
template level. I would instead limit the queryset to 100 when creating the 
queryset and pass that in and then just iterate over it like any other 
queryset, but I think you see what I mean.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/HsGotgeD_XkJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to