2012-05-28 210 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的試試這個。