在RABL模板中渲染ERB模板

jac*_*nry 5 ruby-on-rails erb rabl

我有一个场景,我想用我的JSON传回一条长信息.而不是用字符串连接写出来,我宁愿把一个erb模板放在一起,我可以渲染到我的JSON中.以下是我目前正在尝试的代码:

object @invitation

node(:phone_message) do |invitation| 
  begin
    old_formats = formats
    self.formats = [:text] # hack so partials resolve with html not json format
    view_renderer.render( self, {:template => "invitation_mailer/rsvp_sms", :object => @invitation})
  ensure
    self.formats = old_formats
  end
end
Run Code Online (Sandbox Code Playgroud)

第一次运行此代码时,一切都按预期工作,但是,第二次运行时遇到问题,因为它说有一个缺少的实例变量(我假设在第一次运行时生成并缓存).

未定义的方法_app_views_invitation_mailer_rsvp_sms_text_erb___2510743827238765954_2192068340 for#(ActionView :: Template :: Error)

有没有更好的方法将erb模板呈现为rabl?

Jur*_*lav 2

您可以尝试独立使用 ERB,而不是通过视图渲染器,如下所示:

object @invitation

node(:phone_message) do |invitation| 
  begin
    template = ERB.new(File.read("path/to/template.erb"))
    template.result(binding)
  end
end
Run Code Online (Sandbox Code Playgroud)

binding是对象上的一个方法(通过内核模块),它返回保存当前上下文的绑定,其中还包括实例变量(@invitation在本例中)

更新:

真的不知道这是否能帮助您取得进一步的进展(我也意识到自您发布此文章以来已经过去一年多了),但这是另一种以独立方式呈现 ERB 模板的方法:

view = ActionView::Base.new(ActionController::Base.view_paths, {})  

class << view  
 include ApplicationHelper
 include Rails.application.routes.url_helpers
end  
Rails.application.routes.default_url_options = ActionMailer::Base.default_url_options
view.render(:file => "path/to/template.html.erb", :locals => {:local_var => 'content'}) 
Run Code Online (Sandbox Code Playgroud)

当我有时间的时候,我应该和 Rabl 一起尝试一下。