【问题标题】:Render ERB Template in RABL Template在 RABL 模板中渲染 ERB 模板
【发布时间】:2012-06-03 05:15:27
【问题描述】:

我有一个场景,我想用我的 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

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

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

有没有更好的方法将 erb 模板渲染成 rabl?

【问题讨论】:

    标签: ruby-on-rails erb rabl


    【解决方案1】:

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

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

    binding 是 Object 上的一个方法(通过 Kernel 模块),它返回包含当前上下文的绑定,其中还包括实例变量(在这种情况下为 @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 一起尝试一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 2012-12-31
      • 2011-05-14
      • 1970-01-01
      • 2017-03-01
      • 2014-12-12
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多