我在 Rails 项目中使用 view 组件。我想在孩子体内使用我父母的翻译。 现在,我有这个:
components
└─ a
├─ component.rb
├─ component.html.erb
├─ component.yml
└─ b
├─ component.rb
└─ component.html.erb
这段代码:
module A
class Component < ViewComponent::Base
end
end
module A
module B
class Component < A::Component
end
end
end
<h1>From A component</h1>
<p><%= t('.hey') %></p>
<h1>From B component</h1>
<p><%= t('.hey') %></p>
en:
hey: Hello from translation
但是生成的html是这样的:
<h1>From A component</h1>
<p>Hello from translation</p>
<h1>From B component</h1>
<p><span class="translation_missing" title="translation missing: fr.a.b.component.hey">Hey</span></p>
为了解释我的问题,我使用了 A 和 B。但是就我而言,A 和 B 之间的模板足够不同,不能使用相同的模板。
看起来
.hey
的相对查找路径开始在基于组件的命名空间下查找。
最简单(也是最好的 IMO)方法是使用组件(和部分)中翻译键的完整路径。
因此,您可以使用
<%= t('.hey') %>
(不带前导句点)来代替 <%= t('hey') %>
。
我曾开发过许多具有多种语言的 Rails 应用程序,相对路径键始终是一个巨大的痛点。如果将视图提取到共享部分、重命名控制器或进行大量更改,相对路径转换就会中断。
我也是使用 i18n-tasks 的忠实粉丝,它使用静态代码分析(如 RuboCop)来帮助防止您以这种方式破坏翻译,但因为它不像 ruby 那样动态,所以它也变得更加有助于使用完整的关键路径。