'Safe Rails HTML translations

Following the rails guides as per the posting title, the YAML local files were set in a Rails 6.1.3 application as follows:

authorisation_request: Payment to be authorised; </br>Final <b>exact charge</b> </br>will reflect <b>delivered goods</b>.
authorisation_request_html: Payment to be authorised; </br>Final <b>exact charge</b> </br>will reflect <b>delivered goods</b>.

In the view, three experiments were conducted:

  <i><%= t('cart.authorisation_request').capitalize %></i>
  <i><%= raw t('cart.authorisation_request_html').capitalize %></i>
  <i><%= t('cart.authorisation_request_html').capitalize %></i>

The first one rendered the tags as expected straight text, the middle one rendered as expected both the break and bold tags.

But the last one was rendered identical to the first. What am I missing?



Solution 1:[1]

When a translation key has the _html suffix, you can call it as if it did not, and it will automatically treat the key as HTML safe.

The way you are displaying the translation key is not as intended, instead of doing:

<%= t('cart.authorisation_request_html').capitalize %>

You should be doing:

<%= t('cart.authorisation_request').capitalize %>

Then the I18n system will see that there is an _html-suffixed variant, and mark that as HTML safe to display as-is. The way you are doing it now, the system would be looking for a key named authorization_request_html_html (double suffixed) and not find it.

More info on Safe HTML Translations: https://guides.rubyonrails.org/i18n.html#using-safe-html-translations

As a side-note, you should probably be capitalizing your source translated text, and not modifying it afterwards with the .capitalize helper. If that text were translated to another language, the capitalization could probably look pretty strange in some languages.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Unixmonkey