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,
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 ofapplication.html.haml
)To change all actions in a certain controller to use another layout file
To change an action to use other layout file
Well, if it's a different view for mobile devices but all desktop versions are the same then you could use JQtouch.
http://railscasts.com/episodes/199-mobile-devices
The above code is taken from the Railscasts example.
Yes, you can use different layouts and stylesheets within the same controllers.
The rails guide on layouts is a good place to start. Look at Section 3 - Structuring Layouts
There are several ways to use a different layout but one of the easiest is to simply add a file with the same name as your controller in the
layouts/
folder. So if your controller isPostsController
then adding alayouts/post.html.haml
would cause rails to use that layout. If no such layout is found, and no other layouts are specified, rails will use the default oflayouts/application.html.haml
If you do not want to go too complex, you can simply do this:
this will do.
I am sure there's plenty of answers to this but here's another one where you can use different layouts per controllers or per action.