LoginSignup
13
10

More than 5 years have passed since last update.

Railsで今月のカレンダーを生成するerbコード

Posted at

railsというよりもactive_supportを使って今月のカレンダーをHTMLで生成するerbコードです。ロジックとしては次の通りです。

  1. 今月の1日の週の月曜日の日付dを得ます。
  2. dから1週間分をループで回します。
  3. ループ内では、ループ内の日cが今月でない分は空欄に、今月であれば日付を入れます。
  4. ループを抜けた後にdを1週間後にずらします。
  5. 2.に戻ります(4回目迄)。
<% today = Date.today%>
<table>
  <caption><%= today.strftime('%Y年%m月')%></caption>
  <tr>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
  <tr>
<% month = today.strftime('%m')%>
<% d = today.at_beginning_of_month.at_beginning_of_week%>
<% 1.upto(5).each do|i|%>
  <tr>
<% (d..d.end_of_week).each do|c|%>
    <th><%= (c.strftime('%m') == month)? c.strftime('%d'): "  "%></th>
<% end %>
  </tr>
<% d = d + 1.week %>
<% end %>
</table>

2017年3月に実行して生成されたHTMLをブラウザから見るとこんな感じになります(上のコードのままだと24日のリンクは付きません)。
calendar.png

13
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10