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!

3 Answers 3

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"

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

2 Comments

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 %} <tr> {% endif %} <td><a href="/{{ f.to_friend.username }}/"><img src="{{ f.to_friend.profile_pic }}" class="small-pic" /><br />{{ f.to_friend.username }}</a></td> {% if forloop.counter == 0 or forloop.counter|divisibleby:3 %} </tr> {% endif %}{% endfor %}
@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 :-)

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.