为ActionMailer渲染不同的视图(模板)

时间:2011-11-21 22:06:21

标签: ruby-on-rails ruby-on-rails-3 actionmailer

我试图从ActionMailer(Rails 3.1.1)中对不同的模板进行条件渲染。我希望大多数用户获得正常的welcome.html.erb模板,但有些用户可以获得特殊的welcome_photographer.html.erb模板。这种类型的东西在ActionController中起作用:

# (in /app/mailers/user_mailer.rb) 
def welcome(user)
  @user = user
  mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...")
  render "welcome_photographer" if @user.is_photographer
end

但渲染不起作用 - 即使welcome.html.erb

,每个人都会获得标准@user.is_photographer == true

3 个答案:

答案 0 :(得分:53)

致电mail()后,您不应该尝试做任何事情。但是,要选择其他模板,您应该将:template_name作为选项传递。例如:

template = @user.is_photographer ? "welcome_photographer" : "welcome"
mail(:to => "#{@user.name} <#{@user.email}>", 
     :subject => "Welcome to ...", 
     :template_name => template)

答案 1 :(得分:9)

Sean Hill的解决方案对我不起作用(Rails 3.2+)。 template_name似乎被忽略了。对我有用的是这样的:

mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...") do |format|
  format.html { render 'templatename' }
end

答案 2 :(得分:9)

搞笑导轨3.2.14这对我不起作用:

mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...") do |format|
  format.html { render 'templatename' }
end

但是这样做:

mail(:to => "#{@user.name} <#{@user.email}>", 
 :subject => "Welcome to ...", 
:template_name => template)