Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 929
AnthonyGalli.com Avatar asked Sep 16 '25 13:09

AnthonyGalli.com


2 Answers

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

like image 196
Richard Peck Avatar answered Sep 19 '25 07:09

Richard Peck


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>
like image 22
Beartech Avatar answered Sep 19 '25 07:09

Beartech