Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3, how add a view that does not use same layout as rest of app?

I could not find any docs or examples on how to structure my app to allow different views in the same controller to use completely different layouts and stylesheets.

Our app was scaffolded and we then used nifty-generators to generate views, then added devise for authentication. We have views and controllers for two models: widgets and companies.

I currently have a single layout: layouts/application.html.haml, I don't see that referenced anywhere so I assume (a rails newbie) that it's always used by naming convention.

I now need to add a couple of views (for mobile browsers) which have a different stylesheet and layout (for example, no login/logout links in the top right), within the same controllers.

How can that be done?

like image 841
jpw Avatar asked Feb 23 '11 11:02

jpw


People also ask

How can you tell Rails to render without a layout?

By default, if you use the :plain 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 and use the . text. erb extension for the layout file.

How should you use nested layouts in Rails?

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. This is an example of typical web application page, almost every site has these blocks. And as a rule the body block differs on each page.


1 Answers

By default, layouts/application.html.haml (.erb if you are not using haml).

In fact, layout file could be set per controller or per action, instead of per view, per view folder.

There are few cases:

To change the default layout file for all controller (ie. use another.html.haml instead of application.html.haml)

class ApplicationController < ActionController::Base   layout "another"    # another way   layout :another_by_method   private   def another_by_method     if current_user.nil?       "normal_layout"     else       "member_layout"     end   end end 

To change all actions in a certain controller to use another layout file

class SessionsController < ActionController::Base   layout "sessions_layout"   # similar to the case in application controller, you could assign a method instead end 

To change an action to use other layout file

def my_action   if current_user.nil?     render :layout => "normal_layout"   else     render :action => "could_like_this", :layout => "member_layout"   end end 
like image 190
PeterWong Avatar answered Sep 23 '22 03:09

PeterWong