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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何在Rails 3中的控件之外渲染模板?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的Rails 3应用程序中似乎无法在控制器之外渲染模板.我已经完成的谷歌帮助是有帮助的,我最终在 http://www.swombat.com/rails-rendering-templates-outside-of-a-contro发现了一些有用的信息.但是,这似乎在Rails 3中被破坏.有没有人有任何想法,我可以如何修复这种方法或者可能知道更好的方法

我的方法

  1. def render_erb(template_path,params)
  2. view = ActionView::Base.new(ActionController::Base.view_paths,{})
  3.  
  4. class << view
  5. include ApplicationHelper
  6. end
  7.  
  8. view.render(:file => "#{template_path}.html.erb",:locals => params)
  9. end

错误

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

解决方法

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

基本上你需要这样做:

  1. class HelloWorldController < AbstractController::Base
  2. include AbstractController::Rendering
  3. include AbstractController::Layouts
  4. include AbstractController::Helpers
  5. include AbstractController::Translation
  6. include AbstractController::AssetPaths
  7. include ActionController::UrlWriter
  8.  
  9. self.view_paths = "app/views"
  10.  
  11. def show; end
  12. end

接着:

  1. HelloWorldController.new.show

将返回渲染到String的视图.

猜你在找的Ruby相关文章