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?
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.
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.
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:
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
class SessionsController < ActionController::Base layout "sessions_layout" # similar to the case in application controller, you could assign a method instead end
def my_action if current_user.nil? render :layout => "normal_layout" else render :action => "could_like_this", :layout => "member_layout" end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With