我正在使用Rails 4.0.3。如何在Rails控制台中呈现一个局部视图?
在控制台中尝试以下代码:
# initial setup
view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new view_paths
# (Optional) include this if your partial uses route helpers:
include Rails.application.routes.url_helpers
av_helper.render "path/to/your/partial"
另外,对于模板:
av_helper.render :template => "path/to/your/template"
更新:原帖作者报告部分渲染行未能正常工作,出现了错误。虽然我没有遇到这种情况,但如果其他人有同样的问题,这是原帖作者指出成功的版本:
av_helper.render :partial => 'tags/tag', :collection => Tag.limit(3)
正如Josh Diehl所指出的那样,您也可以在渲染中使用常规选项,例如locals
。我希望您能够像通常在控制器和视图中使用的所有常规渲染选项一样使用它们。
Josh的例子:
av_helper.render(partial: "tags/tag", locals: {term: term})
av_helper.render(partial: "tags/tag", locals: {term: term})
- Josh Diehllocals
键传递它们;你可以将对象的实例变量转换为哈希表,就像这里所描述的那样,这类似于Rails传递控制器实例变量的方式。 - Paul Richter在Rails 5中,有一种官方的方法可以实现这个功能(详见这个拉取请求):
ApplicationController.render 'templates/name'
该开发者还为Rails 4制作了一个支持此功能的gem:backport_new_renderer
对我而言,在Rails 4.2中让它运作的最佳方式是这个两行代码:
view = ActionView::Base.new('app/views/products', {}, ActionController::Base.new)
output = view.render(file: 'index.html', locals: {:@products => Product.all})
我在 github 上找到了这个解决方案。
#render
无关。 - Chloe