Pavel
Pavel

Reputation: 1974

Rails: send email in different languages

In my app I need to send emails in different languages. How it would be done correctly - make different email templates invite.en.text.erb and invite.de.text.erb for example (not sure that will work), keep email messages in I18n localizations or other solutions maybe?

Upvotes: 1

Views: 911

Answers (2)

Martin Bjeldbak Madsen
Martin Bjeldbak Madsen

Reputation: 180

Use localized views (link to Rails Guide here), which do exactly as you suggest. Simply rename the view files as shown, and they will automatically interact with your Rails localization settings.

To send mails in a given locale depending on the User's locale, email address, or some other logic, you can use the I18n.with_locale(locale) method. An example of a Mailer using a similar method is shown in this SO answer.

I would not suggest doing what HendrikPetertje is suggesting. It clutters your locale file with localization strings that are only used for single views.

Upvotes: 4

HendrikPetertje
HendrikPetertje

Reputation: 123

create the default email files (like the one you would use normaly) and try the instructions below:

In your email file:

<p><%= t('email_line_description_here')%></p>
<p><%= t('email_line2_description_here') %></p>
(etc)

In your config/locales/en.yml (the right indentation is important here)

en:
  # email stuff
  email_line_description_here: "Your email's first line content in English here"
  email_line2_description_here: "Your email's second line content in English here"

In your config/locales/de.yml (the right indentation is important here as well)

de:
  # email stuff
  email_line_description_here: "Your email's first line content in German here"
  email_line2_description_here: "Your email's second line content in German here"

Now when the environment is set to English lines will be translated according to the en.yml if German translation will be done acording to de.yml.

Upvotes: 1

Related Questions