Kryvir Myby
Kryvir Myby

Reputation: 3

Rails: How to I render an existing view in another view?

I've tried to make sense of layouts but got lost..
Also googled & looked at other similar questions on SO but none of them helped.

Say I have MVC's (scaffold'ed) for A and B, creating their ..views/A/index.html.erb and ..views/B/show.html.erb among the rest.

A's index method sets a @a_collection.

Within B's show view I want to:

<p>..stuff for B..</p>
<%= render A's index %>
<p>..some more B-stuff</p>

How can I render A's index in that place in B's show?

Upvotes: 0

Views: 1113

Answers (1)

max
max

Reputation: 102036

You don't typically render a view inside of another view. You use partials to share code across views. For example:

# app/views/products/_product.html.erb
# this is the code you want to reuse
<p>Product Name: <%= product.name %></p>
# app/views/products/index.html.erb
<%= render @products %>
# app/views/stores/show.html.erb

<h1><%= @store.name %></h1>

<h2>Our Products</h2>
<%= render @store.products %>

<%= render @products %> is shorthand for <%= render partial: "product", collection: @products %>.

This is just the implicit rendering - in many cases you'll want to add more partials and render them explicitly. Like for example the _form.html.erb partial that you'll find in the scaffolds thats used to share a form between the create and edit views.

Think of partials like the view equivilent to a function - ideally they should take some input in the form of locals and result in a chunk of HTML.

Upvotes: 1

Related Questions