【问题标题】:Rails: Is there a built translation for "ago"?Rails:“以前”有内置翻译吗?
【发布时间】:2018-10-26 17:46:56
【问题描述】:

Rails 使用 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.10rails-i18n gem 提供时间距离,而不是“之前”。

【问题讨论】:

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


    【解决方案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

    【讨论】:

    • 这应该是公认的答案。遗憾的是它没有包含事实上的标准rails-i18n gem。做德语翻译时会弹出同样的情况,即:about one hour is etwa eine Stunde but! about one hour agovor etwa einer Stunde。请注意,不仅添加了vor,还需要在einer 中额外添加r
    【解决方案2】:

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

    假设@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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多