Render Different View (template) for ActionMailer

非 Y 不嫁゛ 提交于 2019-12-04 09:06:00

问题


I'm trying to do a conditional render of a different template from ActionMailer (Rails 3.1.1). I want most users to get the normal welcome.html.erb template, but some users to get the special welcome_photographer.html.erb template. This type of thing works in 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

But the render doesn't work -- everyone gets the standard welcome.html.erb even if @user.is_photographer == true


回答1:


You shouldn't try to do anything after you call mail(). However, to choose another template, you should pass :template_name as an option. For example:

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



回答2:


The solution from Sean Hill doesn't work for me (Rails 3.2+). template_name seems to be ignored. What worked for me is something like this:

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



回答3:


Funny in rails 3.2.14 This does NOT work for me:

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

However this does:

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


来源:https://stackoverflow.com/questions/8219179/render-different-view-template-for-actionmailer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!