【问题标题】:Rails mailer append_view_path not workingRails 邮件程序 append_view_path 不起作用
【发布时间】:2020-06-04 10:20:09
【问题描述】:

我正在尝试使用append_view_path,以便在发送的每封电子邮件的末尾呈现包含我想要的一些额外信息的部分内容。

我的邮件类如下所示:

class PasswordMailer < ActionMailer::Base
  default :from => CaseCenter::Config::Reader.get('email_from')

  append_view_path Rails.root.join('app','views','password_mailer')

  def password_changed(user)
    @user = user
    mail(:to => user.email, :subject => t('mailer.email_topic_password_changed'))
  end
end

运行时,它不会将我的部分添加到电子邮件的末尾。 (虽然发送了一封电子邮件)。 我的部分位于 app/views/password_mailer/password_changed_template.html.erb 并且只包含一个简单的 HTML 元素。

感谢您的帮助

【问题讨论】:

  • 你有一个无与伦比的括号。把最后一行改成mail(to: user.email, subject: t('mailer.email_topic_password_changed'))
  • @max 感谢您指出这一点。当我输入我害怕的问题时,这是一个错字!我现在已经编辑了。
  • app/views/password_mailer/_password_changed_template.html.erb 应该是这样的。您已经为部分添加了 _
  • 这解释了为什么您没有收到语法错误。此邮件应呈现 app/views/password_mailer/password_changed.html.erb(对 append_view_path 的调用是 superflouos)您可以将该视图添加到问题中吗?
  • @AbhishekAravindan 感谢您的建议,但将第 4 行更改为 append_view_path "app/views/password_mailer/_password_changed_template.html.erb" 并没有改变任何内容。

标签: ruby-on-rails actionmailer


【解决方案1】:

如果我已经理解您要正确执行的操作,您可以使用布局来执行此操作。这与使用 ActionController 进行 MVC 时使用的布局非常相似。

# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  layout 'mailer'
end
class PasswordMailer < ApplicationMailer
  default from: CaseCenter::Config::Reader.get('email_from')
  def password_changed(user)
    @user = user
    mail(to: user.email, subject: t('mailer.email_topic_password_changed'))
  end
end

app/views/layouts/mailer.html.erb:

<!DOCTYPE html>
<html lang="en">
<head>
  # ...
</head>
<body>
  <%= yield %>
  <hr>
  <footer>
    This spam was sent to you by EvilCorp. If you where looking to unsubscribe you are out of luck.
  </footer>
</body>
</html>

app/views/layouts/mailer.txt.erb:

<%= yield %>

-------------------------------------
This spam was sent to you by EvilCorp. 
If you where looking to unsubscribe you are out of luck.

当然,您也可以将页脚分成部分并像在普通视图中一样渲染它:

<!DOCTYPE html>
<html lang="en">
<head>
  # ...
</head>
<body>
  <%= yield %>
  <%= render 'shared/mailer_footer' %>
</body>
</html>

【讨论】:

  • 完美,正是我需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
相关资源
最近更新 更多