Okt*_*tav 7 actionmailer ruby-on-rails-3
我目前正在编写RoR 3.2中的邮件程序,它会发送应根据用户语言进行本地化的邮件.我设法渲染了正确的本地化视图,但是我在某些需要更改区域设置的字段(如主题)方面遇到了一些困难.我已经阅读了一些反对在发送电子邮件之前更改语言环境的帖子.用户有许多不同的语言,这意味着每次向用户发送电子邮件时都要更改我的语言环境.
我知道可以更改区域设置,发送电子邮件,更改区域设置.这不像铁路的方式.这样做有正确的方法吗?
这是一个片段:
class AuthMailer < ActionMailer::Base
add_template_helper(ApplicationHelper)
default :from => PREDEF_MAIL_ADDRESSES::System[:general]
[...]
def invite(address, token, locale)
@token = token
@locale = locale
@url = url_for(:controller => "signup_requests", :action => "new", :token => token.key, :locale => locale)
mail(:subject => "Invitation", :to => address) do |format|
format.html { render ("invite."+locale) }
format.text { render ("invite."+locale) }
end
end
[...]
end
Run Code Online (Sandbox Code Playgroud)
我的看法
auth_mailer
invite.en.html.erb
invite.en.text.erb
invite.it.html.erb
invite.it.text.erb
...
Run Code Online (Sandbox Code Playgroud)
简而言之,在这种情况下,我想使用@locale本地化:subject,但不是通过运行:I18n.locale = locale
Sim*_*tsa 30
可以暂时更改全局区域设置.有一个方便的I18n.with_locale方法.此外,ActionMailer会自动翻译主题.
class AuthMailer
def invite(address, token, locale)
@token = token
@locale = locale
@url = url_for(:controller => "signup_requests", :action => "new", :token => token.key, :locale => locale)
I18n.with_locale(locale) do
mail(:to => address)
end
end
end
Run Code Online (Sandbox Code Playgroud)
在语言环境中:
en:
auth_mailer:
invite:
subject: Invitation
Run Code Online (Sandbox Code Playgroud)
Rails 4路:
# config/locales/en.yml
en:
user_mailer:
welcome:
subject: 'Hello, %{username}'
# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
def welcome(user)
mail(subject: default_i18n_subject(username: user.name))
end
end
Run Code Online (Sandbox Code Playgroud)
default_i18n_subject - 使用[mailer_scope,action_name]范围下的Rails I18n类翻译主题.如果它未在指定范围内找到主题的翻译,则它将默认为action_name的人性化版本.如果主题具有插值,则可以通过插值参数传递它们.
归档时间: |
|
查看次数: |
6530 次 |
最近记录: |