16

Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code:

<div id="right_pod">
{%for i in rangeLength%}
    <div class="user_pod" >
        {{c.i.0.from_user}}
    </div>
{% endfor %}

This currently outputs nothing :( If I replace "i" with 0...{{c.0.0.from_user}}...it will output something.. (the first user 10 times)

1
  • 2
    Please provide the structure of c. Otherwise this is hard to interpret. Commented Apr 24, 2009 at 10:05

3 Answers 3

28

Do you need i to be an index? If not, see if the following code does what you're after:

<div id="right_pod">
{% for i in c %}
    <div class="user_pod">
        {{ i.0.from_user }}
    </div>
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

Ideally I need i to be an index so I can limit the amount of users to loop over. Should I be doing this in the Controller before passing c to the template?
+1 for doing this in the controller layer; the view shouldn't contain business logic like that.
-1 for necessarily doing this is the controller. Suppose you need the full list in other parts of the page. It's wasteful to pass in the full list and the truncated list. In such a case you should just pass the full list and use the slice filter suggested by @sotangochips.
15

Please read the entire documentation on the template language's for loops. First of all, that iteration (like in Python) is over objects, not indexes. Secondly, that within any for loop there is a forloop variable with two fields you'll be interested in:

Variable            Description
forloop.counter     The current iteration of the loop (1-indexed)
forloop.counter0    The current iteration of the loop (0-indexed)

Comments

9

You should use the slice template filter to achieve what you want:

Iterate over the object (c in this case) like so:

{% for c in objects|slice:":30" %}

This would make sure that you only iterate over the first 30 objects.

Also, you can use the forloop.counter object to keep track of which loop iteration you're on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.