Reputation: 5167
My main.py
has the following variables:
'booking_times':
{
'Today': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00'],
'Tue': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00'],
'Wed': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00']
}
In my view I would like to display them in table:
-----------------------
Today | Tue | Wed | // line 1
9:00 | 9:00 | 9:00 | // line 2
12:00 | 12:00 | 12:00 |
I have 2 questions:
(1) As an example, how would I loop through for line 2 which are each a <td>
html tag?
(2) My line 1 is as follows, but it outputs as Tue | Today | Wed
instead of Today | Tue | Wed |
:
{% for day in booking_times %}
<td>{{day}}</td>
{% endfor %}
Thanks!
Upvotes: 1
Views: 255
Reputation: 37249
Assuming you are using Python, here is one thing you could try. Note that this starts with a slightly different setup of your booking_times
variable, but hopefully the concept makes sense. The general idea is that we first create a sort order that we will use to sort our values. We then use zip
to create a new list-of-lists, which will begin with the days and then follow with the hours in each subsequent list.
booking_times = {
'Today': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00'],
'Tue': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00'],
'Wed': ['9:00', '12:00', '14:00', '15:00', '19:00', '20:00']
}
# Create a new booking_times variable that is a list-of-list,
# leading with the 'days' and followed by one list for each time
sorted_keys = ['Today', 'Tue', 'Wed']
booking_times = [sorted_keys] + zip(*(booking_times[s] for s in sorted_keys))
Here is what booking_times
looks like at this point in time when iterated over with a simple for row in booking_times: print row
:
['Today', 'Tue', 'Wed']
('9:00', '9:00', '9:00')
('12:00', '12:00', '12:00')
('14:00', '14:00', '14:00')
('15:00', '15:00', '15:00')
('19:00', '19:00', '19:00')
('20:00', '20:00', '20:00')
You can then pass that value into your template and iterate over it in essentially the same way you are above:
{% for day in booking_times %}
<tr>
{% for item in day %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
I can't test the templating right now, but this outputs the following when modified to work with simple print statements:
Today Tue Wed
9:00 9:00 9:00
12:00 12:00 12:00
14:00 14:00 14:00
15:00 15:00 15:00
19:00 19:00 19:00
20:00 20:00 20:00
This may deviating a bit far from your current setup, so happy to adjust if necessary.
Upvotes: 2