我试图从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
答案 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)