Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在邮件gem中使用body-erb模板?_Ruby_Email_Pony - Fatal编程技术网

Ruby 如何在邮件gem中使用body-erb模板?

Ruby 如何在邮件gem中使用body-erb模板?,ruby,email,pony,Ruby,Email,Pony,我想使用作为邮件中的主体erb模板。当我把它放在小马宝石上时,它就起作用了 post 'test_mailer' do Mail.deliver do to ['test1@me.com', 'test2@me.com'] from 'you@you.com' subject 'testing' body erb(:test_mailer) # this isn't working end end private fields = [1, 2] # s

我想使用作为邮件中的主体erb模板。当我把它放在小马宝石上时,它就起作用了

post 'test_mailer' do
  Mail.deliver do
    to ['test1@me.com', 'test2@me.com']
    from 'you@you.com'
    subject 'testing'
    body erb(:test_mailer) # this isn't working
  end
end

private

fields = [1, 2] # some array
ERB文件

<% fields.each do |f| %>
  <%= f %>
<% end %>

假设您最初使用小马的Sinatra路线如下所示:

post 'test_mailer' do
  Pony.mail :to => ['test1@me.com', 'test2@me.com'],
            :from => 'you@you.com',
            :subject => 'testing',
            :body => erb(:test_mailer)
end
您可以看到,此处的电子邮件属性由哈希指定。当切换到使用邮件gem时,它的属性由在特定上下文中调用的块定义,以便这些特殊方法可用

我认为问题可能与在块内调用
erb
有关。以下是一些您可以尝试的东西:

尝试以可以传递到块中的方式生成ERB:

post 'test_mailer' do
  email_body = erb :test_mailer, locals: {fields: fields}
  Mail.deliver do
    to ['test1@me.com', 'test2@me.com']
    from 'you@you.com'
    subject 'testing'
    body email_body
  end
end
或者全局调用ERB,而不是使用sinatra助手:

post 'test_mailer' do
  context = binding
  Mail.deliver do
    to ['test1@me.com', 'test2@me.com']
    from 'you@you.com'
    subject 'testing'
    body ERB.new(File.read('views/test_mailer.erb')).result(context)
  end
end

您试图在哪里运行此代码?这是rails还是sinatra应用程序?这个
erb
函数从哪里来,它知道从符号
:test_mailer
中找到erb模板的位置吗?这是Sinatra应用程序,当我切换到“Pony”mailer时,它会自动检查
视图/test_mailer.erb
文件。所以在这个示例中,你基本上是想用邮件替换Pony?对我更新了问题。如果在这个erb文件中我有一个返回数组的私有方法,我不明白这是怎么发生的。你能举一个ERB模板的例子吗?好的,我现在明白了。通常,您不会这样做。通常将模板变量指定为(
@fields=[1,2]
)。为了传递局部变量,您应该在局部散列中将变量传递给模板。我已经为您的case.thx更新了代码示例。我想从ruby脚本中使用它(没有sinatra或其他)。我想出了这个,而且很管用