I'm using Rails 4.0.3. How do I render a partial from the Rails console?
Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
Ruby on Rails Views Partials Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates. To create a partial, create a new file that begins with an underscore: _form.html.erb.
A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.
Rails can render a raw file from an absolute path. This is useful for conditionally rendering static files like error pages. This renders the raw file (it doesn't support ERB or other handlers). By default it is rendered within the current layout.
Try this (in the console):
# 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"
Also, for templates:
av_helper.render :template => "path/to/your/template"
Update: The OP reported the partial rendering line did not work, and generated an error. I didn't encounter that, but if others do, this is the version the OP indicated was successful:
av_helper.render :partial => 'tags/tag', :collection => Tag.limit(3)
As Josh Diehl pointed out, you can also use the usual options like locals
in the render. I would expect you should be able to use all the usual render options normally used in controllers and views.
Josh's example:
av_helper.render(partial: "tags/tag", locals: {term: term})
There is an official way to do this in Rails 5 (cf this pull request):
ApplicationController.render 'templates/name'
The developer also made a gem to support this in Rails 4: backport_new_renderer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With