【问题标题】:How to store translations that are shared across different views in Rails?如何在 Rails 中存储跨不同视图共享的翻译?
【发布时间】:2013-10-05 11:14:18
【问题描述】:

我正在使用翻译文件来管理我的 Rails 应用程序的各种语言:

fr:
  books:
    index:
      title: "Livres"

Rails 存储出现在多个视图中的title 的方式是什么

这根本不是 DRY,因此不是我想要的:

fr:
  books:
    index:
      title: "Livres"
    new:
      title: "Livres"
    edit:
      title: "Livres"

现在我正在做这样的事情:

fr:
  books:
    title: "Livres"

但这是惯例吗?

我没有在其中指定任何视图的名称,所以我想知道这是否是一种好习惯。

感谢您的任何意见。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 internationalization translation rails-i18n


    【解决方案1】:

    说,您需要存储书籍模型的翻译。您应该将它们存储在:

    en.active_record.models.book
    

    而且,所有书籍属性都应该放在:

    en.active_record.attributes.book.title
    

    为每个视图保留翻译可能不是一个好主意,因为:

    1) 正如你所指出的,它不是 DRY。

    2) 翻译需要很长时间才能加载到内存中。因此,它们中的更多会增加服务器启动时间。

    【讨论】:

    • 好的,这就是我最终所做的。感谢您的帮助。
    • 好的。但是,如果它不是模型属性怎么办?或者一堂课。假设我想要编辑和新视图共享的翻译?
    【解决方案2】:

    我通常喜欢为视图添加一个共享部分,这样您仍然可以使用速记。

    fr:
     books:
       shared: &shared
        title: Livres
        thing_with_variable: "%{count} things"
       index:
        <<: *shared
        thing: thing
       new:
        <<: *shared
        other_thing: other thing
       edit:
        <<: *shared
    

    然后在 index、new 等视图中,你都可以使用速记。

    <%= translate('.title') %>
    <%= translate('.thing_with_variable', count: 2) %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      相关资源
      最近更新 更多