我知道已经有一个被接受的答案了,但是这个问题让我有所思考,我想分享一下Rails i18n yml文件的另一种结构供您考虑/批评。
鉴于我想要:
1. 保持默认应用程序结构,以便在视图中可以使用简写的“懒惰”查找,如`t('.some_translation')`,
2. 尽可能避免字符串重复,特别是那些不仅相同,而且上下文/含义也相同的单词,
3. 只需更改一次键就能反映在所有引用它的地方,
对于一个类似于这样的
config/locales/en.yml文件:
activerecord:
attributes:
user:
email: Email
name: Name
password: Password
password_confirmation: Confirmation
models:
user: User
users:
fields:
email: Email
name: Name
password: Password
confirmation: Confirmation
sessions:
new:
email: Email
password: Password
我可以看到有很多重复的内容,像"Email"和"Password"这样的单词在各自的视图中含义明确。如果我决定把"Email"改成"e-mail",那么去逐个更改会很烦人,所以我想重构字符串以引用某种字典。因此,可以在文件顶部添加一个带有一些
&
锚点的字典哈希表,比如这样:
dictionary:
email: &email Email
name: &name Name
password: &password Password
confirmation: &confirmation Confirmation
activerecord:
attributes:
user:
email: *email
name: *name
password: *password
password_confirmation: *confirmation
models:
user: User
users:
fields:
email: *email
name: *name
password: *password
confirmation: *confirmation
sessions:
new:
email: *email
password: *password
每当您在视图中获得超过一个完全相同的单词/短语时,您可以将其重构为字典。如果基本语言中键的字典翻译对于目标语言没有意义,那么只需更改目标语言中引用值为静态字符串或将其作为目标语言字典的额外条目添加即可。我相信如果它们变得太大和难以处理,每种语言的字典都可以重构为另一个文件。
这种方式的i18n yaml文件结构似乎在我尝试的一些本地测试应用程序中运行良好。我希望美妙的
Localeapp将来会提供对这种定位/引用的支持。但是无论如何,所有这些关于字典的讨论肯定不可能是一个原创的想法,所以YAML中是否存在其他锚定引用问题,或者可能与整个“字典”概念有关的其他问题?还是最好完全删除默认后端并使用
Redis或其他东西替换它?