Ruby on rails 如何在Rails 3中的控制器外部渲染模板?

Ruby on rails 如何在Rails 3中的控制器外部渲染模板?,ruby-on-rails,Ruby On Rails,在Rails 3应用程序中,我似乎无法在控制器之外呈现模板。我做的谷歌搜索很有帮助,我最终在网站上找到了一些有用的信息。然而,Rails 3似乎打破了这一点。有没有人知道我如何修复这个方法,或者知道更好的方法 我的方法: def render_erb(template_path, params) view = ActionView::Base.new(ActionController::Base.view_paths, {}) class << view

在Rails 3应用程序中,我似乎无法在控制器之外呈现模板。我做的谷歌搜索很有帮助,我最终在网站上找到了一些有用的信息。然而,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
我做了一个和一个解释

基本上,您需要这样做:

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

将返回呈现为字符串的视图。

基于Hubert建议的方法,我在Rails 3.1项目中完成了以下内容

我需要在普通视图中呈现一个分部,并在资产中重新使用它(在app/assets/javascripts下)


您可以使用render_anywhere gem在控制器外部渲染模板。

以下是正确的博客链接:对于Rails 4,我必须为ActionView::Layouts添加一个include:“include ActionView::Layouts”。对于Rails 4,include以及ActionView::Rendering
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
<%
class FauxController < AbstractController::Base
  include AbstractController::Rendering
  # I didn't need layouts, translation or assetpaths, YMMV
  include AbstractController::Helpers
  include Rails.application.routes.url_helpers
  helper MyHelper # the partial references some helpers in here 

  # Make sure we can find views:
  self.view_paths = Rails.application.config.paths["app/views"]

  def show
    render :partial => "/my_controller/my_partial.js"
  end
end

%>
<%= FauxController.new.show %>