Haml - if-else with different indentations
I am trying to make a calendar with Rails and Haml .
The dates used are relative to a variable called @dates
. This is a range Date
that contains the first and last days that will appear on the calendar. The first day is always Sunday, and the last day is Monday.
I am planning to display a typical one column calendar on a weekday (Sunday will be the first day of the week) using an HTML table.
So, I need to put a %tr
and then %td
on Sundays, but the rest of the time I just need it %td
.
I am having problems modeling in Haml. It seems like it requires different levels of indentation and something I don't like. Here's my failed attempt:
%table
%tr
%th= t('date.day_names')[0] # Sunday
%th= t('date.day_names')[1]
%th= t('date.day_names')[2]
%th= t('date.day_names')[3]
%th= t('date.day_names')[4]
%th= t('date.day_names')[5]
%th= t('date.day_names')[6] # Monday
-@dates.each do |date|
- if(date.wday == 0) # if date is sunday
%tr
%td=date.to_s
- else
%td=date.to_s
It doesn't work the way I want it to. %td
for non-Sundays it is displayed outside %tr
:
<tr>
<td>2010-04-24</td>
</tr>
<td>2010-04-25</td>
<td>2010-04-26</td>
<td>2010-04-27</td>
<td>2010-04-28</td>
<td>2010-04-29</td>
<td>2010-04-30</td>
<tr>
<td>2010-05-01</td>
</tr>
<td>2010-05-02</td>
<td>2010-05-03</td>
...
I tried to add two more spaces in else
, but then Haml complained about wrong indentation.
What's the best way to do this?
Note. I'm not interested in rendering a calendar using unordered lists. Please consider using the table as one of the problematic constraints.
a source to share
Evgeny's comment put me on the right track.
Here's a solution that works using rails in_groups_of (link is dead now):
%table(cellspacing="0" cellpadding="0")
%tr
%th= t('date.day_names')[0]
%th= t('date.day_names')[1]
%th= t('date.day_names')[2]
%th= t('date.day_names')[3]
%th= t('date.day_names')[4]
%th= t('date.day_names')[5]
%th= t('date.day_names')[6]
- @dates.to_a.in_groups_of(7) do |week|
%tr
- week.each do |day|
%td=day.to_s
Note that I had to convert Range to an array - ranges don't seem to be implemented in_groups_of
.
a source to share
%table
%tr
%th= t('date.day_names')[0] # Sunday
%th= t('date.day_names')[1]
%th= t('date.day_names')[2]
%th= t('date.day_names')[3]
%th= t('date.day_names')[4]
%th= t('date.day_names')[5]
%th= t('date.day_names')[6] # Monday
%tr
-@dates.each do |date|
%td=date.to_s
This should give you
<tr>
<td>2010-04-24</td>
<td>2010-04-25</td>
<td>2010-04-26</td>
<td>2010-04-27</td>
<td>2010-04-28</td>
<td>2010-04-29</td>
<td>2010-04-30</td>
</tr>
a source to share