【问题标题】:Rails 6 internationalization - what has changed?Rails 6 国际化 - 发生了什么变化?
【发布时间】:2020-03-15 15:44:39
【问题描述】:

我开始了一个全新的 Rails 6 项目,并一直想弄清楚为什么显然刚刚起作用(这不是我启动的第一个应用程序),但失败了...... 所以我创建了一个没有额外宝石和home#index 页面的虚拟简单rails 应用程序:

<h1>Home#index</h1>
<p>
    <%= t('hello.world') %>
</p>

然后我为config/locales/en.yml添加了上述key的翻译:

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.yml 中的引号,有时在复制粘贴时会替换为不正确的符号
  • 我检查了,根本没有复制/粘贴,一切似乎都是正确的,你可以检查我创建的Gist。我还改在模板中使用双引号:``,但没有成功:(.
  • 尝试重新启动服务器,也许?当出现如此奇怪的错误时,我总是运行spring stop &amp;&amp; rails s
  • 重启后还是一样。

标签: ruby-on-rails rails-i18n ruby-on-rails-6


【解决方案1】:

如果你想嵌套它,那么你不能将字符串值分配给父级,而是这样做

en:
  hello:
    world: "Hello World!"

然后,在erb 中,这将起作用

<%= t('hello.world') %>

试一试。

【讨论】:

  • 我的错,就是这样!谢谢你。不知道为什么我在地球上留下了价值:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多