【问题标题】:How do I render a partial from the Rails console?如何从 Rails 控制台渲染部分内容?
【发布时间】:2014-03-31 11:30:06
【问题描述】:

我使用的是 Rails 4.0.3。如何从 Rails 控制台渲染部分内容?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

在 Rails 5 中有一种官方方法可以做到这一点(参见 this pull request):

ApplicationController.render 'templates/name'

开发人员还在 Rails 4 中制作了一个 gem 来支持这一点:backport_new_renderer

【讨论】:

    【解决方案2】:

    对我来说,让它在 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.

    【讨论】:

      【解决方案3】:

      试试这个(在控制台中):

      # 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})
      • 酷,感谢@JoshDiehl,说得通。我希望所有常用的渲染选项都能正常工作。我会将其添加到答案中。
      • 有什么方法可以让实例变量像 Rails 视图中常用的那样可用?
      • @justingordon 我不知道为什么我没有早点听到你的问题,抱歉耽搁了。您可以通过locals 键传递它们,如上所述;您可以将对象的实例变量转换为像here 所述的哈希,这类似于Rails passes controller instance variables
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      • 2013-08-18
      • 2014-01-12
      相关资源
      最近更新 更多