Skip to content

Customizing the text html displayed within an event

jeffschuil edited this page Jan 11, 2011 · 1 revision

You can customize the text or html that is displayed within the events by modifying the code within the calendar block. If you used the generator, then this is found in your calendar_helper.rb, inside the event_calendar method.

By default, it will simply show the event's name, and attempt to link to the event by its ID. If you used the 'all_day' option, then it will also insert the time of those events that aren't marked as lasting all day. It also includes a simple 'display_event_time' helper method as a starting point.

For example, if you wanted to add localization to how event times are displayed, you could do something like this:

  def event_calendar
    # args is an argument hash containing :event, :day, and :options
    calendar event_calendar_opts do |args|
      event, day = args[:event], args[:day]
      html = %(<a href="/events/#{event.id}" title="#{h(event.name)}">)
      html << display_event_time(event, day)
      html << %(#{h(event.name)}</a>)
      html
    end
  end

  def display_event_time(event, day)
    time = event.start_at
    if !event.all_day and time.to_date == day
      t = I18n.localize(time, :format => "%l:%M%p")
      %(<span class="ec-event-time">#{t}</span>)
    else
      ""
    end
  end

Of course, you can customize the time's format as desired. The default method attempts to shorten the displayed time as much as possible, leaving out the minutes when the time falls on the hour, and dropping the 'am'. You could achieve something similar using localization like so (courtesy of felipediesel):

  def display_event_time(event, day)
    time = event.start_at
    if !event.all_day and time.to_date == day
      format = (time.min == 0) ? "hour" : "hour_and_minute"
      format += time.strftime("%p") == "PM" ? "_pm" : "_am"
      t = I18n.localize(time, :format => :"calendar.#{format}")
      %(<span class="ec-event-time">#{t}</span>)
    else
      ""
    end
  end

With something like this in your locale file(s):

  es:
    time:
      formats:
        calendar:
          hour_am: "%l"
          hour_and_minute_am: "%l:%M"
          hour_pm: "%l%p"
          hour_and_minute_pm: "%l:%M%p"
      am: "am"
      pm: "pm"