AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

Rails: How to Render Conditional Based Upon 'pages/home.html.erb'

In the tbody section of application.html.erb I wanted to render for the current_user two sidebars if he is on the home page and just one sidebar for every other page.

  <body>
    <% if current_user.present? %>
      <% if 'pages/home.html.erb' %> # Not Working As a Conditional
        <div class="container">
          <div class="col-md-3">
            <%= render 'layouts/valuations' %>
          </div>
          <div class="col-md-6">
            <% flash.each do |name, msg| %>
              <%= content_tag(:div, msg, class: "alert alert-info") %>
            <% end %>
            <div id="modal-holder"></div>
            <%= yield %>
          </div>
          <div class="col-md-3">
            <%= render 'layouts/sidebar' %>
          </div>
        </div>
      <% else %>
        <div class="container-fluid">
          <div class="container">
            <div class="col-md-9">
              <% flash.each do |name, msg| %>
                <%= content_tag(:div, msg, class: "alert alert-info") %>
              <% end %>
              <div id="modal-holder"></div>
              <%= yield %>
            </div>
            <div class="col-md-3">
              <%= render 'layouts/sidebar' %>
            </div>
          </div>
        </div>
      <% end %>
    <% else %>
    <div class="container">
      <% flash.each do |name, msg| %>
        <%= content_tag(:div, msg, class: "alert alert-info") %>
      <% end %>
      </div>
      <%= yield %>
    <% end %>
  </body>

Upvotes: 4

Views: 1969

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

Firstly, you're looking for current_page?:

<% if current_page?(controller: "pages", action: "home") %>
   ... 
<% end %>

This is notoriously rickety though (what happens if you change your pages controller?).


What you'll be better doing is what beartech suggested, setting a variable which you can ping in your layout:

#app/controllers/pages_controller.rb
class PagesController < ApplicationController
   def home
       @home = true
   end
end 

#app/views/layouts/application.html.erb
<if @home %>
   ...
<% end %>

I would match this with the use of partials:

#app/views/layouts/application.html.erb
<%= render "shared/sidebar" if @home %>
<%= render "shared/flash" %>

This gives you the ability to split your code into more manageable chunks. We do it here:

enter image description here

Upvotes: 3

Beartech
Beartech

Reputation: 6431

In your :index action for your home page you can set a variable like:

def index
  @home_page = true
...

And then you can just do something like:

<body>
  <% if current_user.present? %>
    <% if @home_page %> 
      <div class="container">
        <div class="col-md-3">
          <%= render 'layouts/valuations' %>
        </div>

Upvotes: 2

Related Questions