Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put partials shared by the whole application in Rails?

Where would I go about placing partial files shared by more than one model? I have a page called crop.html.erb that is used for one model - Photo. Now I would like to use it for another model called User as well.

I could copy and paste the code but that's not very DRY, so I figured I would move it into a partial.

Since it's shared between two models - where would I place that partial?

Thanks!

like image 348
Yuval Karmi Avatar asked Mar 05 '10 04:03

Yuval Karmi


People also ask

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

How should you use nested layouts in rails?

Rails provides us great functionality for managing layouts in a web application. The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.

What is the layout in Ruby on Rails?

A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and to use it.


2 Answers

The Rails convention is to put shared partials in /app/views/shared.

like image 129
John Topley Avatar answered Sep 20 '22 18:09

John Topley


Update

Layout inheritance is now in the guides under layout and rendering Template inheritance works similarly.

Rails 3.1 and following versions implement template inheritance, so I think the correct place for shared partials is now /app/views/application/, say you are in products#index you can do the following:

-# products#index = render @products.presence || 'empty'  -# /app/views/application/_empty.html.haml There are no items 

btw it's application because the connection is the controller inheritance, so this assumes ProductsController < ApplicationController

This way if you implement /app/views/products/_empty.html.haml that will be taken, the above is a fallback for all the missing partials, and I can't check right now, but I think even for the template itself...

Railscast: template inheritance!

like image 30
ecoologic Avatar answered Sep 20 '22 18:09

ecoologic