Rails 中的不同文本 i18n

Different text i18n in Rails

在我的 rails 应用程序中,我有一个部分(file1/_partial.html.erb)必须以两种形式呈现 file2/form1.html.erbfile3/_partial.html.erb,我想知道什么是i18n 部分文本的最佳解决方案

其实我在做的是

<%= (t :to_ranslate, :scope => 'file2.form1' ) %>

  file2:
    form1:
      to_ranslate: "translated"

这是有效的,但我想知道是否有解决方案,我可以根据模板进行不同的翻译,因此对于相同的部分,我将根据呈现的位置使用不同的文本

如果您在包含在不同模板中时不需要不同的翻译,您可以只使用 "Lazy Lookup",如 4.1.4 中所述:http://guides.rubyonrails.org/i18n.html#looking-up-translations

它也适用于渲染局部,例如:

in file1/_partial.html.erb
<%= (t '.to_translate') %>

in the translations.yml:
en:
  file1:
    _partial:
      to_translate: "translated"

根据渲染的位置使用不同的翻译,就像这样(未经测试但原则应该有效):

in file1/_partial.html.erb
<%= (t "#{translation_scope.to_s}.to_translate') %>

in file2/form1.html.erb
<%= render '/file1/partial', translation_scope: 'file2._partial' %>

in file3/_partial.html.erb
<%= render '/file1/partial', translation_scope: 'file3._partial' %>

in the translations.yml
en:
  file1:
    _partial:
      to_translate: "translated"
  file2:
    _partial:
      to_translate: "translated"
  file2:
    _partial:
      to_translate: "translated"

这样做的好处是,当您不指定 translation_scope(回退到默认值)时以及您传递它时它仍然有效。 这就是为什么我更喜欢它而不是像你一样使用范围:'xx' 的原因。 而且整个界面看起来有点像视图中的继承,到处都是一样的结构。

以更抽象和复杂的方式,也可以为此使用回退,但在此处的示例中,这将是过分的。在较大的项目中,实现这样的东西可能是有意义的。

据我所知 rails 默认是国际化的 只需像往常一样放置文本,它应该没问题。

参考:http://guides.rubyonrails.org/i18n.html