jpheos
jpheos

Reputation: 458

In ruby View Components, is possible to access parent translation from child?

I am using view component in rails project. I want use translation from my parent inside a child. For now, I have this:

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

And this code:


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

But the html generated is that:

<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>

To explain my problem I use A and B. But In my case my template between A and B is enough different to not use the same.

Upvotes: 0

Views: 370

Answers (1)

Unixmonkey
Unixmonkey

Reputation: 18784

It appears that the relative lookup path for .hey starts looking under a namespace based on the component.

The easiest (and best IMO) way is to use full paths to the translation keys in your components (and partials).

So instead of <%= t('.hey') %>, you use <%= t('hey') %> (without the leading period).

I've worked on many Rails apps that have multiple languages, and relative-path keys are always a huge pain-point. If you extract a view out to a shared partial, rename a controller, or a number of changes, relative path translations break.

I'm also a big fan of using i18n-tasks, which uses static code analysis (like RuboCop) to help prevent you from breaking translations in this manner, but because it is not as dynamic as ruby, it also becomes more helpful to use full key paths.

Upvotes: 0

Related Questions