加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails 3中的控件之外渲染模板?

发布时间:2020-12-16 20:03:11 所属栏目:百科 来源:网络整理
导读:我的Rails 3应用程序中似乎无法在控制器之外渲染模板.我已经完成的谷歌帮助是有帮助的,我最终在 http://www.swombat.com/rails-rendering-templates-outside-of-a-contro发现了一些有用的信息.但是,这似乎在Rails 3中被破坏.有没有人有任何想法,我可以如何修
我的Rails 3应用程序中似乎无法在控制器之外渲染模板.我已经完成的谷歌帮助是有帮助的,我最终在 http://www.swombat.com/rails-rendering-templates-outside-of-a-contro发现了一些有用的信息.但是,这似乎在Rails 3中被破坏.有没有人有任何想法,我可以如何修复这种方法或者可能知道更好的方法?

我的方法:

def render_erb(template_path,params)  
   view = ActionView::Base.new(ActionController::Base.view_paths,{})  

   class << view  
    include ApplicationHelper  
   end  

   view.render(:file => "#{template_path}.html.erb",:locals => params)  
  end

错误:

ActionView::Template::Error: ActionView::Template::Error
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/whiny_nil.rb:48:in `method_missing'
    from /Users/mikegerstenblatt/Desktop/bluetrain/lib/test.html.erb:17:in `_lib_test_html_erb__366962844_2173671680_68830'
    from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/template.rb:135:in `send'
    from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/template.rb:135:in `render'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications.rb:54:in `instrument'
    from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/template.rb:127:in `render'
    from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/render/rendering.rb:59:in `_render_template'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications.rb:52:in `instrument'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications.rb:52:in `instrument'
    from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/render/rendering.rb:56:in `_render_template'
    from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/render/rendering.rb:26:in `render'
    from /Users/mikegerstenblatt/Desktop/bluetrain/app/models/generated_website.rb:45:in `render_erb'
    from (irb):2

解决方法

我做了一个 blog post和一个 gist解释它.

基本上你需要这样做:

class HelloWorldController < AbstractController::Base
  include AbstractController::Rendering
  include AbstractController::Layouts
  include AbstractController::Helpers
  include AbstractController::Translation
  include AbstractController::AssetPaths
  include ActionController::UrlWriter

  self.view_paths = "app/views"

  def show; end
end

接着:

HelloWorldController.new.show

将返回渲染到String的视图.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读