Rails:是否有针对“ ago”的内置翻译?

时间:2018-10-26 17:46:56

标签: ruby-on-rails ruby-on-rails-4 internationalization rails-i18n

前导时间为time_ago_in_words,文档为this

time_ago_in_words(3.minutes.from_now)                 # => 3 minutes

但是,在我们的应用中,我们使用"ago": 3 minutes ago

因此,当“ ago”出现在time_ago之前(例如,在 法语 中),什么是最好的翻译方法:

大约3分钟

这是内置在Rails中吗?

使用 Rails 4.2.10 rails-i18n gem 可以提供时间上的距离,但不能提供“ ago”。

2 个答案:

答案 0 :(得分:1)

您可以使用自定义范围:

https://github.com/rails/rails/blob/fc5dd0b85189811062c85520fd70de8389b55aeb/actionview/lib/action_view/helpers/date_helper.rb#L75

time_ago_in_words(3.minutes.ago, scope: 'datetime.distance_in_words_ago') # => 3 minutes ago

,您需要将此添加到您的语言环境(en.yml)

en:
  datetime:
    distance_in_words_ago:
      x_days:
        one: 1 day ago
        other: "%{count} days ago"
      x_minutes:
        one: 1 minute ago
        other: "%{count} minutes ago"
      x_months:
        one: 1 month ago
        other: "%{count} months ago"
      x_years:
        one: 1 year ago
        other: "%{count} years ago"
      x_seconds:
        one: 1 second ago
        other: "%{count} seconds ago"

https://github.com/rails/rails/blob/fc5dd0b85189811062c85520fd70de8389b55aeb/actionview/lib/action_view/helpers/date_helper.rb#L78

答案 1 :(得分:1)

我认为您只需要将时间作为变量传递给翻译。 然后使用yml s语言,您可以将字符串的其余部分放在需要的位置。

假设@product.purchased_time_ago返回time_ago_in_words()

# app/views/products/show.html.erb
<%= t('time_ago', time: @product.purchased_time_ago) %>

# config/locales/en.yml
en:
  time_ago: "%{time} ago"

# config/locales/fr.yml
fr:
  time_ago: "Il y a %{time}"

这直接来自docs