0

the problem is this:

I have my application layout file looks like this:

app/views/layouts/application.html.erb
...
<section>
  <%= yield %>
</section>
...

Now what I would like to do is set the class of the section element dynamically, depending on what view I'm rendering

for instance, if I'm rendering a Dashboard view from: /app/views/admin/news_items/index.html.erb

I would like the class of the section element dynamically be set to "dashboard":

<section class="dashboard">
   <%= yield %>
</section>

Is this possible with Rails?

thanks for your help,

Anthony

Toontje
  • 1,415
  • 4
  • 25
  • 43

2 Answers2

2

As far as i can understand you want specific namespaces to have different layouts right?

You can achieve easily this by specifying different layout for different controllers/namespaces

# In DashboardController

layout 'dashboard'

The above will use the dashboard.html.erb under app/views/layouts for all the actions that are inside the DashboardController or inherit from it.

I hope that helps

nronas
  • 181
  • 4
  • thanks for your suggestion nronas. I already tried this, but the problem is that I want app/views/layout/dashboard.html.erb from app/views/layouts/application.html.erb, so that I don't have to duplicate all of the layout but can inject the layout specific for Dashboard pages. – Toontje Jul 11 '14 at 12:10
  • Cool! I think what @Vinay suggested is a quick win. But i would put the class name determination into a method on application helper. Something like `def section_class; ...; end` and this will return 'dashboard' for dashboard related stuff(based on controller name) or anything else that you need for different scenarios. – nronas Jul 11 '14 at 12:21
  • I found a - very nice - solution here: http://blog.55minutes.com/2014/02/easier-nested-layouts-in-rails-34/ . Now I have a dashboard layout file (app/views/layouts/dashboard.html.erb) that inherits it's layout from app/views/layouts/application.html.erb – Toontje Jul 11 '14 at 13:05
  • @Toontje yeap the nested inherited layouts will give you what you are looking for, but is not the 'Rails way' IMHO. And also in that article he is saying that is a hack ;). For production code i am trying to avoid 'hack/patch' approaches. – nronas Jul 11 '14 at 15:20
  • if it's a hack, it's a pretty good one :). I now have all my admin pages inherit the dashboard layout. All I had to do was put: layout "dashboard" in the dashboard controller. In the dashboard.html.erb layout I just needed to put the layout specific for the admin pages, the other layout is inherited from application.html.erb – Toontje Jul 13 '14 at 08:12
1

Maybe you could do something like this?

<section class="<%= controller.controller_name %>-<%= controller.action_name %>">

This will add a class like so

<section class="dashboard-show">

Source: https://stackoverflow.com/a/16813823/3651372

Community
  • 1
  • 1
Vinay
  • 333
  • 3
  • 8