Reputation: 52550
I have a lot of different webpages, but most fall into 1 of 6 or 7 categories of pages. For each of these categories of webpages, I have a slightly different look and feel, like different background colors/images. I have the following in views/layout/application.html.erb
:
<header class="sub<% if content_for?(:page_type) %> <%= yield(:page_type) %><% end %>">
And in every single view, I have:
<% content_for :page_type, 'information' %>
But it's really a pain to do that for every single webpage and when I want to change things around I keep having to mess with these (I have a ton of pages). So, instead I'm thinking to just use a variable:
<header class="sub<%= @page_type ? ' ' + @page_type : '' %>">
and for views:
<% @page_type = 'information' %>
The advantage is I could do a before_filter :set_page_type
in the controller and set the page type once for all the views it controls (a big help).
Maybe the best thing for me to do is just use the first folder of the URL as the category of the webpage. I'll have to restructure the URLs, but that might make sense to do so anyway. I do have some top-level pages that would have to remain so.
This has to be a fairly common situation, what is the best way to categorize most pages and use that categorization in layouts?
Upvotes: 0
Views: 83
Reputation: 17744
I’m usually using a helper for the body class — something like this:
def body_class(c = nil)
@body_class ||= [controller.controller_name]
@body_class << c
@body_class.flatten.compact.uniq.join(" ")
end
This will by default include the controller name (you could also include the action etc.. Then I call this helper in views as needed, e.g.
<% body_class "bar" %>
Since the helper always returns a class string, you can then call the same helper in you layout (I use the body
tag), likely without arguments:
<body class="<%= body_class %>">
Which would render in the previous example for a controller called FoosController
the following:
<body class="foos bar">
If you define the helper in e.g. the application controller and make it available to the views using helper_method
, this should hopefully much do what you’re after.
Upvotes: 1