Rails将模板文件作为控制器中的字符串变量

时间:2014-09-23 20:47:23

标签: ruby-on-rails ruby templates

我正在创建一个自定义ActionMailer,它还会在 Twitter 上发送直接消息,并通过 Twilio发送短信 即可。我需要每个人都接收消息正文的参数。我需要将当前模板用作字符串变量。

例如:

# calling send_invite's mail method will load the send_invite template
def send_invite(to)
  mail(to: to) # body parameter is automatically rendered from template
end

现在,如果我修改它以通过其他服务发送:

def send_invite(to, option)
  if option == :email
    mail(to: to) # body parameter is automatically rendered from template
  elsif option == :twitter
    twitter.create_direct_message(to, NEED_TEMPLATE_AS_STRING_HERE)
  elsif option == :sms
    twilio.sms(to, NEED_TEMPLATE_AS_STRING_HERE)
  end
end

我如何获取每个服务调用的模板?会有类似的东西:

message(to, render layout: false)
# or
message(to, IO.read template_path_helper("template") )
# or
message(to, template_helper.to_s)

在这些其他方法中,如何将模板作为我的邮件正文的字符串?什么是 Rails方式来做到这一点?模板是erb文件,需要能够像渲染一样呈现适当的变量。

我需要这样做才能使模板的翻译可用。

1 个答案:

答案 0 :(得分:1)

我认为您可以从控制器创建模板字符串,并将其发送到您的邮件程序,如下所示:

@parsed_template = render_to_string(:partial => 'my_partial', :layout => false, :locals => {:my_object => my_value})

SomeMailer.send_invite(to, option, @parsed_template).deliver