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?
params
method...)? Is there a better 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With