如何在.rb文件中呈现邮件程序模板(无模板文件)

时间:2016-12-26 01:39:36

标签: ruby-on-rails ruby-on-rails-4 rendering actionmailer slim-lang

部分原因在于反应的方便性使得组件中有一小段剪切的模板代码。以下是我到目前为止的情况:

# app/mailers/membership_mailer.rb
# frozen_string_literal: true
class MembershipMailer < ApplicationMailer
  def one_week_expiration(member, renewal, org)
    template = slim(%(
      = content_for :header
        = org.name
      Hello, #{member.name},
      br
      Your membership for #{org.name} is set to expire at
      #{renewal.expires_at.to_s(:short)}.
      br
      Please visit <a href=#{org.url}>#{org.url}</a> to purchase
      a membership renewal.
      br
      br
    ))

    subject = "Your membership for #{org.name} is going to expire soon"
    mail(to: member.email, subject: subject) do |format|
      # there isn't a slim renderer
      format.html { render text: template }
    end
  end
end

我正在为所有电子邮件使用此布局,并将其设置为默认布局application_mailer。

# app/views/layouts/email.html.slim
= stylesheet_link_tag "email"

header
  .shell
    h1 = yield :header

.shell
  br
  = yield :body
  = yield

= render partial: "/shared/email_footer"

我想要所有的渲染方法,但我正在努力的是在哪里找到/弄清楚如何为邮件程序,布局构建模板,并将我想要访问的所有变量传递给模板。

# app/mailers/application_mailer.rb
# frozen_string_literal: true
class ApplicationMailer < ActionMailer::Base
  default from: APPLICATION_CONFIG['support_email']
  layout 'email'

  # taken from slim/test/block rendering / helper
  def slim(source, options = {}, &block)
    scope = options.delete(:scope)
    locals = options.delete(:locals)
    Slim::Template.new('', {}) { source }.render(scope, locals, &block)
  end
end

最终,我会有erb,arbre等。

总而言之,我在调用mail(...){...}时,我希望能够在ruby中定义我的模板,而不是在模板文件中定义,因为我不喜欢将邮件程序和模板分开(在文件系统中..为什么超出了这个问题的范围,我只是想解决现在在ruby中呈现的问题)。

1 个答案:

答案 0 :(得分:0)

看起来最简单的方法是使用render_anywhere,它只是一个非常精简的控制器,然后让我们访问render方法。

所以,我对课程的更改如下:

在我的邮件中

  def one_week_expiration(member, renewal, org)
    template_environment = {
      org: org,
      member: member,
      renewal: renewal
    }

    template = slim(env: template_environment) do
      %q(
        = content_for :header
          = org.name

        h3 Hello, #{member.name},

        | Your membership for #{org.name} is set to expire at #{renewal.expires_at.to_s(:short)}.
        br
        | Please visit <a href=#{org.url}>#{org.url}</a> to purchase a membership renewal.
        br
        br
      )
    end

    subject = "Your membership for #{org.name} is going to expire soon"

    mail(to: member.email, subject: subject) do |format|
      format.html { render text: template }
    end
  end

然后是重要的位(在application_mailer中)

require 'render_anywhere'

class ApplicationMailer < ActionMailer::Base
  layout 'email'

  default from: APPLICATION_CONFIG['support_email']



 def slim(env: {})
    raise 'No Block Given' unless block_given?

    RenderAnywhere::RenderingController.new.render_to_string(
      inline: yield, layout: 'email', type: :slim, locals: env
    )
  end
end

就是这样。