vegansound
vegansound

Reputation: 23

Rails - What's the right way to modify html classes in application.html.erb?

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:

  1. It didn't work. I couldn't figure out how to make a controller's instance variable accessible to the application.html.erb file.
  2. I'm not sure if that's the right way to do this, or the rails way to do this.

Any suggestions would be highly appreciated. :)

Upvotes: 2

Views: 524

Answers (2)

panmari
panmari

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

craig.kaminsky
craig.kaminsky

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

Related Questions