You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby View Components:子组件如何访问父组件翻译资源?

ViewComponent子组件复用父组件翻译的解决方案

问题场景

在Rails项目中使用ViewComponent时,子组件继承父组件后,无法直接复用父组件翻译文件中的内容,子组件调用t('.hey')会出现翻译缺失。

文件结构

components
└─ a
   ├─ component.rb
   ├─ component.html.erb
   ├─ component.yml
   └─ b
      ├─ component.rb
      └─ component.html.erb

组件代码

父组件A (a/component.rb)

module A
  class Component < ViewComponent::Base
  end
end

子组件B (a/b/component.rb)

module A
  module B
    class Component < A::Component
    end
  end
end

组件模板

父组件模板 (a/component.html.erb)

<h1>From A component</h1>
<p><%= t('.hey') %></p>

子组件模板 (a/b/component.html.erb)

<h1>From B component</h1>
<p><%= t('.hey') %></p>

父组件翻译文件 (a/component.yml)

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>

解决方案

方法1:直接指定父组件翻译路径

在子组件模板中显式调用父组件的翻译键,或者使用相对路径向上跳转:

<!-- 方式1:绝对路径 -->
<p><%= t('a.component.hey') %></p>

<!-- 方式2:相对路径 -->
<p><%= t('../hey') %></p>

方法2:重写子组件的translation_key方法

ViewComponent允许通过重写translation_key方法,改变组件的翻译路径。修改子组件B的代码:

module A
  module B
    class Component < A::Component
      # 直接指定父组件的翻译键
      def translation_key
        'a.component'
      end
    end
  end
end

如果需要更通用的写法,让子组件自动继承父组件的翻译键:

module A
  module B
    class Component < A::Component
      def translation_key
        self.class.superclass.translation_key
      end
    end
  end
end

这样子组件调用t('.hey')时,会自动使用父组件的翻译路径。

方法3:在父组件翻译文件中映射子组件路径

使用YAML锚点,在父组件翻译文件中为子组件路径复用父级翻译内容:

en:
  hey: &hey Hello from translation
  b:
    component:
      hey: *hey

这样子组件的t('.hey')会自动匹配到复用的翻译内容。

内容的提问来源于stack exchange,提问作者jpheos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:22:52