LoginSignup
12
0

More than 3 years have passed since last update.

超簡単!erbで動的にシンプルなカレンダを作る方法

Last updated at Posted at 2020-11-30

アドベントカレンダの記念すべき1日目なのでカレンダネタです。

この記事を読んだらできること

  • 任意の範囲でカレンダが作れる
  • 特定の日だけデザインを変えたり、文章を変えたりできる

いきなりですがコード。

<% # この辺りはViewModelあたりに入れるのがお行儀がいい %>
<% # カレンダにしたい月を含む日付であればなんでもいい %>
<% target_month = Date.new("2020-12-01") %>
<% # カレンダのはじまりの日(例では月初) %>
<% start_day = target_month.beginning_of_month %>
<% # カレンダの終わりの日(例では月末) %>
<% last_day  = target_month.end_of_month %>

<% # カレンダ本体 %>
<table>
  <thead>
    <tr>
      <% %w[日 月 火 水 木 金 土].each do | day | %>
        <%= content_tag :th, day %>
      <% end %>
    </tr>
  </thead>

  <tbody>
    <tr>
      <% # 月初部分の曜日調整 %>
      <% start_day.wday.times do %>
        <%= content_tag :td, '' %>
      <% end %>

      <% (start_day..last_day).each do | date | %>
        <%= content_tag :td, date.day %>
        <% # wday == 6 は土曜日なので、tableの次の行(tr)へと移行する %>
        <%== '</tr><tr>' if date.wday == 6 %>
      <% end %>
    </tr>    
  </tbody>
</table>

今回は月初から月末までのオーソドックスなものですが start_day last_day を変えれば任意の範囲でのカレンダが作れます。
また、 <%= content_tag :td, day.day %> を下記のようにすればクリスマスだけ表示を変えたりCSSのclassを付与したりもできます。

<% if date.month == 12 && date.day == 25 %>
  <%= content_tag :td, 'Xmas', class: 'xmas' %>
<% else %>
  <%= content_tag :td, date.day %>
<% end %>

シンプルな分、カスタマイズが自由なカレンダだとおもいます。

12
0
0

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
12
0