Rails i18n supports lazy lookup so that if you have a locales file shaped like this:
en: newsletter_cta: title: "Stay Up To Date With The Latest Happenings"
You can reference the value in
t('.title') when in
In many Rails applications, I extract partials to encapsulate components so any HTML/CSS oriented team member doesn't have to learn how to write helper methods when writing components; and so we don't wind up with copy-pasted code that would necessitate massive pain when upgrading or shifting the underlying UI framework.
Here's an example of a bootstrap section:
# app/views/application/_section.html.erb <section class="section-wrap"> <div class="container"> <%= yield %> </div> </section>
Which I can then use in other views, like this:
# app/views/_newsletter_cta.html.erb <%= render "section" do %> <h2><%= t('newsletter_cta.title') %></h2> <%= render "cta-button", text: t('newsletter_cta.title') %> <% end %>
This works fine, so long as don't rely on lazy lookup and I hardcode the full lookup string for the translation.
However, as soon as I use lazy lookups the translation is not found.
# app/views/_newsletter_cta.html.erb <%= render "section" do %> <h2><%= t('.title') %></h2> <%= render "cta-button", text: t('.title') %> <% end %>
Tracing through to the translate method in ActionView::Helpers::TranslationHelper we see that it relies on a method named
scope_key_by_partial which in turn, relies on an instance variable
Do any of y'all know of a way to preserve the virtual path while using partials with blocks? Is there a gem somewhere that changes this behavior? I'm a bit surprised no one else has stumbled into this.