Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails layout per controller

Tags:

I have a home controller and a news controller. I want both of these controller to use the application.html.erb layout file and in addition to that, for home, use the home layout and news, use the news layout. and then render a specific view. Is this possible in rails?

In other words, I don't want to specify a layout per view, but per controller, both inheriting from application.html.erb layout.

What i want to do is remove the redundancy of adding the top navigation bar and including javascript/css in every single layout file. I'd rather include that in one file, and do controller specific layout with another layout, and then finally render the view.

Thanks

like image 545
0xSina Avatar asked Jul 03 '12 00:07

0xSina


People also ask

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 are layouts in Rails?

In Rails, layouts are pieces that fit together (for example header, footer, menus, etc) to make a complete view. An application may have as many layouts as you want. Rails use convention over configuration to automatically pair up layouts with respective controllers having same name.

How can you tell Rails to render without a layout *?

By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.

What are 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.


1 Answers

You can tell a controller to use a specific layout, eg

class HomeController < ApplicationController   layout 'home' end  class NewsController < ApplicationController   layout 'news' end 

These will expect the layouts in app/views/layouts/home.html.erb etc

like image 114
Tim Peters Avatar answered Jan 27 '23 10:01

Tim Peters