Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render a partial from the Rails console?

Tags:

I'm using Rails 4.0.3. How do I render a partial from the Rails console?

like image 758
Chloe Avatar asked Feb 27 '14 19:02

Chloe


People also ask

How do you render partials?

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() .

What is partial view in Rails?

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.

What is use of partials in Rails?

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.

How does render work in Rails?

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.


2 Answers

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})
like image 54
Paul Richter Avatar answered Sep 20 '22 11:09

Paul Richter


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

like image 30
Nicolas Maloeuvre Avatar answered Sep 16 '22 11:09

Nicolas Maloeuvre