6

I am trying to create a dynamic HTML table with 3 columns and 3 rows. Each column will have 3 records from the database so there will be 9 total records displayed (if they have 9 friends. otherwise just however many they have). I am doing this to mainly display small user profile pictures with their friends' usernames on the users homepage. Its going to be a list of 9 of their friends. I am using Django and cannot seem to find a tutorial showing how to display only 3 records per row if I retrieve 9 total records. Any help would be appreciated whether it be a link to a tutorial or info on how to solve this issue. Thanks!

vt-cwalker
  • 795
  • 2
  • 16
  • 34

3 Answers3

9

you can use the forloop.counter and do something like:

<table>
    <tr>
{% for person in people %}
        <td>{{ person }}</td>
    {% if not forloop.last and forloop.counter == 3 or forloop.counter == 6 %}
    </tr>
    <tr>
    {% endif %}
{% endfor %}
    </tr>
</table>

or roll a custom template tag. One here looks like its doing what you want.

looks like this SO question is related:

Render one queryset into 2 div columns (django template)

[EDIT] : should be "counter" not "count"

Community
  • 1
  • 1
dting
  • 38,604
  • 10
  • 95
  • 114
1

This snippet might also be useful in this context: Group sequence into rows and columns for a TABLE

arie
  • 18,737
  • 5
  • 70
  • 76
0

you can use {% if friends|length == 9 %} to check if you have 9 records.

goh
  • 27,631
  • 28
  • 89
  • 151
  • I found the answer.. I did the following after tweaking what you said @amateur. {% for f in friends %} {% if forloop.counter == 0 or forloop.counter|divisibleby:4 %} {% endif %}
    {{ f.to_friend.username }}
    {% if forloop.counter == 0 or forloop.counter|divisibleby:3 %} {% endif %}{% endfor %}
    – vt-cwalker Apr 26 '11 at 03:35
  • @Corey if your going to post a comment with code in it at least use backtiks ie: ` to wrap that code in so its displayed correctly :-) – chris Nov 15 '12 at 20:26