0

In my quest to keep my application views as DRY as possible I've encountered a little snag. My appliation.html.erb incorporates a static sidebar menu. Each of my main controllers incorporates a secondary sidebar menu (essentially a submenu). I can take the code that renders the menu out of application.html.erb and put it in each of my views and change the secondary sidebar there, but this produces a lot repetition in my views.

I saw this SO post and looked at this page, but I was unable to get either idea to work. I was thinking that I could put something like:

<% provide(:submenu, 'layouts/sidebars/sidebar_customers_contacts') %>

at the top of each view and use that to render the associated partial by doing

<% content_for(:submenu) do %>
   <%= render :partial => :submenu %>
<% end %>

from the application.html.erb but of course that didn't work.

This is my current application.html.erb:

  <div class="side">
    <%= render 'layouts/sidebar' %>
    <%= render 'layouts/sidebars/sidebar_dashboard' %><!-- this needs to load a sidebar based on the controller that calls it. Each view of the controller will get the same sidebar.  -->
  </div>
  <div class="main-content">
    <%= yield %>
  </div>

I feel like I'm making this more difficult than it really is. Is there a simple way to do this?

mack
  • 2,715
  • 8
  • 40
  • 68

1 Answers1

0

Rails provides a helper called controller_name which you can read more about here.

Assuming you adhere to your own naming conventions, this should work as-is. If you decide some controllers don't get a sidebar, you may need to throw in some conditionals...

application.html.erb

<div class="side">
  <%= render "layouts/sidebar" %>
  <%= render "layouts/sidebars/#{ controller_name }" %>
</div>
<div class="main-content">
  <%= yield %>
</div>

EDIT Sorry, my mistake was using single quotes instead of double-quotes. You cannot use #{string interpolation} within single quotes. Source

Lanny Bose
  • 1,811
  • 1
  • 11
  • 16
  • Thanks @Lenny Bose. This is perfect if I can get it to work. I tried controller_name, controller.controller_name, '@controller.controller_name' and I get 'The partial name (layouts/sidebars/#{ controller_name }) is not a valid Ruby identifier' for each one. is my syntax incorrect? I am using syntax shown in the answer and even some variations of it. Any ideas what I'm doing wrong? – mack Oct 20 '15 at 12:31
  • The error points in the right direction. Rails wasn't interpolating the controller name into its value, but rather was just using the variable name. My edit above should work. – Lanny Bose Oct 20 '15 at 21:04
  • Awesome! That was about the only variation I hadn't tried and of course it is the only one that works. : ) Thank you for your help. – mack Oct 22 '15 at 17:54
  • Glad I could help! Happy Rails-ing! – Lanny Bose Oct 22 '15 at 18:38