Papadeltasierra
Papadeltasierra

Reputation: 243

i18n rails lazy look-up from a helper?

I'm using I18n lazy look-up e.g. t('.field') with Rails 4 and from both controllers and views, I18n does the appropriate look-up. But it doesn't from helpers and I was wondering whether there is a reason why or a solution?

It seems that if I create a helper function, say 'help()', and call it from multiple different views, I have to define the same I18n strings twice (yes, I use aliases ;-) ). So I need to define both

Any nice ways to avoid this?

Upvotes: 2

Views: 526

Answers (1)

max
max

Reputation: 102026

I18n.t uses the current request as a context. So when you call:

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

From apps/views/users/show.html.erb it will use the key users.show.hello. However on apps/views/pets/show.html.erb the translation is missing as you have noticed.

It does not matter if you are calling it in your view or in a helper since both use the view context.

If you want to avoid this you would simply state the translation key explicitly:

<%= t('users.show.hello') %>

If you want to use dynamic lookup and fall back to a fixed key you could do it like this:

<%= t('.hello', default: t('users.show.hello')) %>

Upvotes: 2

Related Questions