Reputation: 23
I work on an existing rails application. For some pages, I need to add a class to the "content" div, and other divs which reside in the application.html.erb file. Say I have div class="content", and for some pages I need div class="content widgetgrid". I'm wondering what's the "right way" to do this, or more importantly the Rails-y way to do this?
I thought about defining an instance variable and passing it to the application.html.erb file. well:
Any suggestions would be highly appreciated. :)
Upvotes: 2
Views: 524
Reputation: 3827
If it's only a simple thing such as a class that is different, instead of making a full new layout you could use content_for
, as described here. In your view you would then do
<% content_for :my_additional_classes, 'some classes you want' %>
and then read it out in your layout application.html.erb
in the appropriate place. For example
# Layout stuff ...
<div class="always_used_class <%= yield :my_additional_classes %>">
# content...
</div>
# More layout stuff ...
Edit: This assumes you want to set this content in the view (which makes sense, since view related stuff should be defined in the view, that's the railsy way). If you really want to do it in the controller you could also use the following to set the the content
view_context.content_for(:my_additional_classes, 'some_additional_class')
Upvotes: 1
Reputation: 5598
I would, most likely, just use a variety of layout files in such a case. You can apply a controller-specific layout in Rails via:
layout 'some_layout_file'
You can also use a method in the controller to dynamically load a layout (we actually do this at work for an app that uses a different layout based on the subdomain.
layout :set_layout
def set_layout
# some awesome Ruby code here that sets your layout
end
You can also set the layout in the method/action block of your controller as well.
There are many different ways to go about solving your problem ... the above is just how I prefer to approach it.
Upvotes: 0