【发布时间】:2014-03-31 11:30:06
【问题描述】:
我使用的是 Rails 4.0.3。如何从 Rails 控制台渲染部分内容?
【问题讨论】:
-
查看之前的 SO 帖子:stackoverflow.com/questions/8538798/…
-
@GraemeMcLean 这些答案都不是关于
#render。
标签: ruby-on-rails ruby ruby-on-rails-4
我使用的是 Rails 4.0.3。如何从 Rails 控制台渲染部分内容?
【问题讨论】:
#render。
标签: ruby-on-rails ruby ruby-on-rails-4
在 Rails 5 中有一种官方方法可以做到这一点(参见 this pull request):
ApplicationController.render 'templates/name'
开发人员还在 Rails 4 中制作了一个 gem 来支持这一点:backport_new_renderer
【讨论】:
对我来说,让它在 Rails 4.2 中工作的最好方法是使用这个 twoliner:
view = ActionView::Base.new('app/views/products', {}, ActionController::Base.new)
output = view.render(file: 'index.html', locals: {:@products => Product.all})
我找到了这个解决方案on github.
【讨论】:
试试这个(在控制台中):
# 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"
更新: OP 报告部分渲染线不起作用,并产生错误。我没有遇到过,但是如果其他人遇到过,这是OP指示成功的版本:
av_helper.render :partial => 'tags/tag', :collection => Tag.limit(3)
正如 Josh Diehl 所指出的,您还可以在渲染中使用 locals 等常用选项。我希望您应该能够使用控制器和视图中通常使用的所有常用渲染选项。
乔希的例子:
av_helper.render(partial: "tags/tag", locals: {term: term})
【讨论】:
av_helper.render(partial: "tags/tag", locals: {term: term})
locals 键传递它们,如上所述;您可以将对象的实例变量转换为像here 所述的哈希,这类似于Rails passes controller instance variables。