I18n: What is the difference between using 't(:test_key)', 't('test_key')' and 't('.test_key')'?

半世苍凉 提交于 2019-12-21 21:38:48

问题


I am using Ruby on Rails 3.1 and I would like to know how, when and why I should use one of the following code rather than another on internationalizing my application (I18n gem):

t(:test_key)
t('test_key')
t('.test_key')

That is, what is the "subtle" difference between using t(:test_key), t('test_key') and t('.test_key')? What are best practices about this issue?


回答1:


I think first two are equivalent and you just refer to main key in your translations, fo example

t('hello_world') 
# t(:hello_world) is an equivalent

would reffer to

en:
  hello_world: "Hello world"

However if you use dot notation, its called lazy lookup and it will look deeper in your translation structure based on controller/action notation

So if you use this inside users/index template

t('.hello_world')

it will be resolved to

pl:
  users:
    index:
      hello_world: "Witaj świecie"

You'll find more about internalization in Rails Guides




回答2:


I guess it's a but up to you to decide when you actually want to use the different ones, but I'd prefer to use lazy lookup as much as possible in my views, unless you need to translate some generic component whose keys does not live in the scope of your view.

The reason why I prefer the lazy lookup is that it makes the code look cleaner, and as long as you're familiar with how the i18n gem works, you shouldn't have any trouble knowing where to look for the keys.

On the other hand, if you have such components, they should really live in a partial, a cell or something similar.

One thing worth mentioning abouth the non-lazy ones, are that you can provide them with a scope for where to look for the key in question. Again, it's up to you whether you like t('foo.bar.baz.test_key') or t(:test_key, :scope => 'foo.bar.baz').

It also takes a bunch of other options, but all of this is neatly documented in the rails guide, so I won't explain it further here.



来源:https://stackoverflow.com/questions/8767219/i18n-what-is-the-difference-between-using-ttest-key-ttest-key-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!