【问题标题】:How to embed Ruby code in Rails i18n yml file?如何在 Rails i18n yml 文件中嵌入 Ruby 代码?
【发布时间】:2018-04-29 02:59:48
【问题描述】:

我想根据count参数创建一个可以是单数或复数的句子:

# When count is 1
"This profile still contains 1 post"

# When count is 2
"This profile still contains 2 posts"

使用 Rails i18n 机制,我相信我必须嵌入 Ruby 代码才能获得“post”一词的正确复数形式。我正在尝试像这样构建它,但它不起作用:

# config/locales/en.yml
en:
  message: "This profile still contains %{count} <%= Post.model_name.human(count: count).lowercase %>"

# Output of I18n.translate(:message, count: 2)
"This profile still contains 2 <%= Post.model_name.human(count: count).lowercase %>"

我已经尝试过&lt;%= %&gt;%{ }#{ }{{ }},但都失败了。

是否可以在 i18n 文件中嵌入 Ruby 代码?怎么样?

【问题讨论】:

    标签: ruby-on-rails internationalization


    【解决方案1】:

    根据docs,你应该这样做:

    en:
      message:
        one: This profile still contains 1 post
        other: This profile still contains %{count} posts
    

    然后称呼它:

    I18n.t('message', count: count)
    

    希望对你有帮助!

    【讨论】:

    • 首先,这个Post.model_name.human(count: count).lowercase的输出是什么?我希望它是一个数字?
    • 它的输出是模型的名称,单数或复数,取决于count 的值。文档:apidock.com/rails/v4.2.7/ActiveModel/Name/human
    • 我接受了这个答案,因为它更易于使用和理解,尽管重复了一些单词。但是这两个答案都是好的和有效的。谢谢你和@sovalina。
    【解决方案2】:

    使用pluralize 方法:

    config/locales/en.yml

    en:
      message: "This profile still contains"
    

    查看

    "#{I18n.t('message')} #{Post.count} #{Post.model_name.human.pluralize(Post.count).downcase}."
    
    #=> output : "This profile still contains 1 post." or "This profile still contains XX posts"
    

    它有效,但我建议您将所有视图逻辑放在帮助程序中。

    注意:我使用全局 Post.count 作为示例,但您可以使用任何您想要的计数作为 user.posts.count 等...

    【讨论】:

    • 像这样使用pluralize 仅适用于英语。在其他语言中,它只是在单词后面附加一个“s”,这并不总是正确的。但如果这样写,解决方案将是正确的:"#{I18n.t('message')} #{Post.count} #{Post.model_name.human(count: Post.count).downcase}."。假设yml文件包含模型名称的翻译,包括one:other:
    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多