Styling text in localization files — bold, italic, etc

11,874

Check out documentation it says:

Third, it'll mark the translation as safe HTML if the key has the suffix “_html” or the last element of the key is the word “html”. For example, calling translate(“footer_html”) or translate(“footer.html”) will return a safe HTML string that won't be escaped by other HTML helper methods. This naming convention helps to identify translations that include HTML tags so that you know what kind of output to expect when you call translate in a template.

So you need to append suffix _html to your key and now you can use html in your locales.

For example this is your locale file:

en:
  welcome:
    html: '<b>Hello!</b> This is first way to style your locales!'
  welcome_html: '<b>Hi again!</b> This is second way to style your locales!'

Now just set I18n.t 'en.welcome.html' or I18n.t 'en.welcome_html' in your views. That's all! :)

Share:
11,874
coreyward
Author by

coreyward

I currently work at Figma as a web developer. I work on our marketing website, our DesignSystems publication, and our Config user conference website. Outside of Figma I do freelance work, mostly involving Gatsby/React and Sanity.io. I used to do a lot of full-stack development using Ruby on Rails (and PHP before that), but these days I tend to do more Jamstack/front-end work.

Updated on June 29, 2022

Comments

  • coreyward
    coreyward almost 2 years

    What techniques/methods are there for dealing with emphasized or stylized text in localized strings?

    For example, how might a brief title such as the one below (4–8 words) be italicized?

    Welcome to the Machine, John.

    Is there a more efficient way than 3 lookups, plus a variable to define the structure?