Meliborn
Meliborn

Reputation: 6645

Render partial template base on condition in Ruby on Rails

I have 2-column layout. Some controller has left column, some not. What is the best way to render it depend on controller? Now, it look likes that:

<% if params[:controller] != 'page' %>
        <div id="navigation" class="l"><%= render "layouts/left-menu" %></div>
    <% end  %>

It's bad, bad monkey code.

Upvotes: 0

Views: 1373

Answers (2)

accounted4
accounted4

Reputation: 1705

Edit: Changed my solution, OP wanted condition to depend on action and controller.

In your base helper, define a method like this:

# app/helpers/application_helper.rb
module ApplicationHelper
  def has_left_menu?
    @has_left_menu.nil? ? 
      true : # <= default, change to preference
      @has_left_menu
  end
end

In your application controller:

# app/controllers/application_controller.rb
class ApplicationController
  def enable_left_menu!
    @has_left_menu = true
  end
  def disable_left_menu!
    @has_left_menu = false
  end
end

In your view or layout, change your check to this:

<% if has_left_menu? %>
    <div id="navigation" class="l"><%= render "layouts/left-menu" %></div>
<% end  %>

Now you can disable/enable the left menu in before_filters or anywhere else in your action:

class UsersController < ApplicationController
  # enable left menu for "index" action in this controller
  before_filter :enable_left_menu!, :only => [:index]

  # disable left menu for all actions in this controller
  before_filter :disable_left_menu!

  def index
    # dynamic left menu status based on some logic
    disable_left_menu! if params[:left_menu] == 'false'
  end
end

Upvotes: 2

Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

In your controller you use layout like this

#PublicController is just an example
class PublicController < ApplicationController
  layout "left-menu"
end

And in the views/layouts folder you put the left-menu.html.erb

with a stylesheet_link_tag to your spesific css file

<%= stylesheet_link_tag 'left-menu' %>

You can learn more at rails guides

Upvotes: 1

Related Questions