2012-05-28 67 views
5

我有一个场景,我想用我的JSON传回长消息。我宁愿将可以呈现到我的JSON中的erb模板放在一起,而不是用字符串连接写出来。下面是我目前正试图代码:在RABL模板中渲染ERB模板

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 

一切正常第一次运行这些代码,但是,我遇到问题我第二次运行它,因为它说,有一个丢失的实例变量(我认为这是第一次运行时生成和缓存的)。

未定义的方法 _app_views_invitation_mailer_rsvp_sms_text_erb___2510743827238765954_2192068340 为#(::的ActionView ::模板错误)

有没有更好的办法来渲染ERB模板到Rabl的?

回答

2

你可以尝试使用ERB作为独立的,并通过视图渲染不会,就像这样:

object @invitation 

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

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'}) 

当我有时间,我实际上应该与Rabl的试试这个。