我该如何在Rails控制台中呈现局部视图?

22
我正在使用Rails 4.0.3。如何在Rails控制台中呈现一个局部视图?

1
可能是重复的问题:如何在Rails控制台中调用控制器/视图方法? - user740584
请查看此前的SO帖子:https://dev59.com/PV7Va4cB1Zd3GeqPJGHL - cat3045
2
@GraemeMcLean 这些答案都与 #render 无关。 - Chloe
3个回答

42

在控制台中尝试以下代码:

# 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})

1
使用本地变量:av_helper.render(partial: "tags/tag", locals: {term: term}) - Josh Diehl
很酷,谢谢@JoshDiehl,很有道理。我希望所有通常的渲染选项都能起作用。我会把它加到答案中。 - Paul Richter
有没有办法使实例变量在Rails视图中像通常使用的那样可用? - justingordon
@justingordon,不知道为什么我之前没有看到你的问题,抱歉回复晚了。你可以像上面描述的那样通过locals键传递它们;你可以将对象的实例变量转换为哈希表,就像这里所描述的那样,这类似于Rails传递控制器实例变量的方式。 - Paul Richter

29

在Rails 5中,有一种官方的方法可以实现这个功能(详见这个拉取请求):

ApplicationController.render 'templates/name'

该开发者还为Rails 4制作了一个支持此功能的gem:backport_new_renderer


13

对我而言,在Rails 4.2中让它运作的最佳方式是这个两行代码:

view = ActionView::Base.new('app/views/products', {},  ActionController::Base.new)
output = view.render(file: 'index.html', locals: {:@products => Product.all})

我在 github 上找到了这个解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接