BBQ Chef
BBQ Chef

Reputation: 696

Localize a whole sentense passing it a datetime

I googled around but didn't find an answer - even if I guess it isn't tricky!

I'd like to localize a sentense that icludes date and time parameter. I want to pass it a complete datetime.

de_txt.yml

  de:
    article:
      will_be_published_at: 'Wartet auf Veröffentlichung am %a %e. %b %Y um %H:%M Uhr'

My function with d is out of the database, field type is datetime (second line is the one of my problem)

  def icon_article_will_be_published_at(d)
    alt = t('article.will_be_published_at', d)
    image_tag("#{root_url}images/famfamfam/icons/date_next.png", :title => alt, :alt => alt, :class => "icon")
  end

more about d

d.inspect # => Sat, 03 Dec 2011 14:07:00 CET +01:00

I can't figure it out and would appreciate help.

Upvotes: 0

Views: 120

Answers (2)

mliebelt
mliebelt

Reputation: 15525

I would propose the following:

  • Split what you want to do in 2 steps:
  • Define a special format :um as described in the Rails Guide to I18n

    de:
      article:
        will_be_published_at: 'Wartet auf Veröffentlichung am %datetime'
      time:
        formats:
          um: "%a %e. %b %Y um %H:%M Uhr"
    
  • Call it then in the following snippet:

    time = l(d, :format => :um)
    alt = t('article.will_be_published_at', :datetime => time)
    

I could not test it, but it should work.

Upvotes: 0

Marek Příhoda
Marek Příhoda

Reputation: 11198

For this, you will need the I18n#l method, not the translate method. It's a bit tricky, because you need a separate time format in the translations file (de.yml). This is one way to do it (adjust as necessary):

In config/locales/de.yml:

de:
  time:
    formats:
      article_published_at: 'Wartet auf Veröffentlichung am %a %e. %b %Y um %H:%M Uhr'

Testing it in the console:

I18n.locale = :de

I18n.l Time.now, :format => :article_published_at

Upvotes: 1

Related Questions