Search code examples
ruby-on-railsstring-interpolationruby-on-rails-7

Interpolation not working for Rails app in locale file


I am trying to localize text in a Rails 7 app using interpolation to display the distance of a park from the user, but it's rendering as text instead of the distance value.

config/locales/en.yml

en:
  parks:
    _park_cards:
      km_away: "%{park.distance.round(0)} km away"

app/views/parks/_park_cards.html.erb

<%= t("parks._park_cards.km_away") %>

What I want to render in the view:

27 km away

What I'm getting in the view:

%{park.distance.round(0)} km away

What am I doing wrong?


Solution

  • The I18n method just supports simple variable passing and not arbitrary Ruby expressions:

    en:
      parks:
        _park_cards:
          km_away: "%{distance} km away"
    

    Formatting distance is the role of the view or whatever is calling the translation.

    <%= t("parks._park_cards.km_away", distance: park.distance.round(0)) %>
    

    This is actually a good thing since it prevents you from putting the complexity into the translations (DRY) and you can pass of the work of translations to less technically skilled people without the fear of it blowing up your application - worst case scenario is just that it looks bad.