Change sidebar content for certain Rails controllers
Most (or even all) pages in your Rails application have the same sidebar content, but just one needs to show something different? On your login and registration pages, you don’t want to show the last five books/movies/events, but a marketing text why people should signup for your site? You’re currently using an
if/elsif/else statement to switch content based on the controller’s name?
Time to learn about Rails’ Template Inheritance. Your application layout probably looks something like this right now:
Instead of rendering the sidebar’s content inline, let’s render a partial:
# app/views/application.html.erb ... <div class="col col-sidebar"> <%= render 'sidebar' %> </div>
Now add a
_sidebar.html.erb partial in the following directories:
# app/views/registrations/_sidebar.html.erb Users will only see this when on a registration page.
# app/views/sessions/_sidebar.html.erb Users will only see this when on a session page.
# app/views/application/_sidebar.html.erb Users will see this all other times.