Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate email messages body using the I18n gem?

I am using Ruby on Rails 3.1.1 and I am trying to translate email messages body. I created/stated all necessary "things" (YAML files, key/value pairs, ...) to make the I18n gem to work: email messages are sent without problems using the default language (:en).

Then I added a new language and made all that had to be done to make the I18n gem to work with another language and to get always a locale=de parameter in URLs.

class ApplicationController < ActionController::Base
  before_filter :set_locale

  def set_locale
    if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
      I18n.locale = params[:locale]
    end
  end

  ...
end

However when I sent an email, even if the locale is properly set (eg: locale=de), sent email message are not translated (those still use the default :en language).

How can I make the I18n to translate email messages body?


  • I read the Localized ActionMailer Templates for Rails blog post but it is old and I have not tested that...
  • I read the Rails I18n and emails blog post and I tested that. It works, but how can handle translation in my case (I am using the params method...)? Is there a better solution?
like image 931
Backo Avatar asked Jan 12 '12 14:01

Backo


1 Answers

Solution

In your railsproject make a mailer (read http://guides.rubyonrails.org/action_mailer_basics.html how to make one). For example UserMailer.

rails g mailer UserMailer

Define a method for example mail_user.

def mail_user(user)
    @user = user
    mail(:to => "test example <[email protected]>", :subject => "hello")
end

Now define views. For example: mail_user.de.html.erb and mail_user.en.html.erb. Put your translations in there. If you want to translate variables seperatly use:

<%= I18n.t("foo.bar") %>

When you do this, ensure you have a en.yml and de.yml translation! Define a translation like the following example:

foo:
    bar: hello

You should be ready to go.

How this works

ActionMailer works the following way. You can create mailer models which inherit from ActionMailer::Base. Like ActionController the models have associated views (templates) in the /app/views/ directory.

Now here is the technical part and why this all magicly works. ActionController and ActionMailer default include AbstractController::Rendering directly or indirectly (ActionController::Metal::Rendering). AbstractController::Rendering uses ActionView as default library for its template rendering engine and includes AbstractController::ViewPaths and an instance of I18n proxy to find localized views. To learn more i'd like to refer to the ActionPack source code on github.

To get to the point. ActionView allows you to use localisation in your templates: See Rails guide: Action View Overview , Chapter Localized views.

like image 176
Antek Drzewiecki Avatar answered Oct 30 '22 17:10

Antek Drzewiecki