Rails 6 国际化——改变了什么?
Rails 6 internationalization - what has changed?
我开始了一个全新的 Rails 6 项目,但一直想弄清楚为什么明显有效(这不是我启动的第一个应用程序)却失败了...
所以我创建了一个简单的虚拟 rails 应用程序,没有额外的 gems 和一个 home#index
页面:
<h1>Home#index</h1>
<p>
<%= t('hello.world') %>
</p>
然后我在 config/locales/en.yml
中添加了上述键的翻译:
en:
hello: "Hello !"
world: "Hello World!"
并遵守 1 个制表符缩进。
导航到 localhost:3000/home/index
时出现奇怪的错误:
/Users/serguei/.rvm/gems/ruby-2.7.0/gems/i18n-1.8.2/lib/i18n.rb:195: warning: The called method `translate' is defined here
Rendered home/index.html.erb within layouts/application (Duration: 6.2ms | Allocations: 3150)
Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.0ms | Allocations: 5045)
ActionView::Template::Error (can not load translations from /Users/serguei/projects/rails/draft-app/config/locales/en.yml: #<Psych::SyntaxError: (<unknown>): did not find expected key while parsing a block mapping at line 2 column 3>):
1: <h1>Home#index</h1>
2: <p>
3: <%= t('hello.world') %>
4: </p>
app/views/home/index.html.erb:3
当将调用的翻译更改为 hello
时:
<h1>Home#index</h1>
<p>
<%= t('hello') %>
</p>
并从 en.yml
文件中删除最后一行:
en:
hello: "Hello !"
有效。
为什么这样?自 Rails 5 以来发生了什么变化?我们不能再在语言环境文件中使用嵌套翻译了吗? Rails guides 没什么特别的。还是我遗漏了什么?
将 rails-i18n gem 添加到 Gemfile 没有解决问题。
- Rails版本:6.0.2.1
- Ruby 版本:ruby 2.7.0p0(2019-12-25 修订版 647ee6f091)[x86_64-darwin19]
如果要嵌套它,则不能将字符串值分配给父级,而是这样做
en:
hello:
world: "Hello World!"
然后,在erb
,这将起作用
<%= t('hello.world') %>
试一试。
我开始了一个全新的 Rails 6 项目,但一直想弄清楚为什么明显有效(这不是我启动的第一个应用程序)却失败了...
所以我创建了一个简单的虚拟 rails 应用程序,没有额外的 gems 和一个 home#index
页面:
<h1>Home#index</h1>
<p>
<%= t('hello.world') %>
</p>
然后我在 config/locales/en.yml
中添加了上述键的翻译:
en:
hello: "Hello !"
world: "Hello World!"
并遵守 1 个制表符缩进。
导航到 localhost:3000/home/index
时出现奇怪的错误:
/Users/serguei/.rvm/gems/ruby-2.7.0/gems/i18n-1.8.2/lib/i18n.rb:195: warning: The called method `translate' is defined here
Rendered home/index.html.erb within layouts/application (Duration: 6.2ms | Allocations: 3150)
Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.0ms | Allocations: 5045)
ActionView::Template::Error (can not load translations from /Users/serguei/projects/rails/draft-app/config/locales/en.yml: #<Psych::SyntaxError: (<unknown>): did not find expected key while parsing a block mapping at line 2 column 3>):
1: <h1>Home#index</h1>
2: <p>
3: <%= t('hello.world') %>
4: </p>
app/views/home/index.html.erb:3
当将调用的翻译更改为 hello
时:
<h1>Home#index</h1>
<p>
<%= t('hello') %>
</p>
并从 en.yml
文件中删除最后一行:
en:
hello: "Hello !"
有效。 为什么这样?自 Rails 5 以来发生了什么变化?我们不能再在语言环境文件中使用嵌套翻译了吗? Rails guides 没什么特别的。还是我遗漏了什么?
将 rails-i18n gem 添加到 Gemfile 没有解决问题。
- Rails版本:6.0.2.1
- Ruby 版本:ruby 2.7.0p0(2019-12-25 修订版 647ee6f091)[x86_64-darwin19]
如果要嵌套它,则不能将字符串值分配给父级,而是这样做
en:
hello:
world: "Hello World!"
然后,在erb
,这将起作用
<%= t('hello.world') %>
试一试。