BrightBlue
BrightBlue

Reputation: 417

RoR 4.2: Find the view/template name from within a layout

I am trying to get the main view/template name from the layout, essentially so that I can target specific views with CSS without having to resort to [data-action=new], [data-action=create], etc.

Is there a way to do this without monkey patching ActionView::TemplateRenderer or similar, as that seems awfully heavy handed for something that should be quite simple.

Given that controller_name and action_name are readily available, I am failing to understand why there is no similar method for the view to be / being rendered.

Upvotes: 0

Views: 72

Answers (2)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42919

If you are using haml there's a nice helper method called page_class this adds the controller and actions as css classes, when added to the <body> you can target single pages with css
( if you're not using haml then i guess you could implement your own view helper to do this same funtion )

%body{ class: page_class }

The rendered view would be

<body class="my_controller my_action">

Then in the css you could use it to add conditions ( assuming you're targeting a div with id called my_div )

#my_div {
  color: red;
  .my_action & {
     color: blue
  }
}

The output will become

#my_div {
    color: red;
}
.my_action #my_div {
    color: blue;
}

This will make the color red in all pages, and blue only when the action is my_action

Upvotes: 1

Antarr Byrd
Antarr Byrd

Reputation: 26179

You can access request.fullpath within the view. See rails api

Upvotes: 0

Related Questions