Charlie Davies
Charlie Davies

Reputation: 1834

Conditional Rendering of partial in Rails

I have the controller:

class PagesController < ApplicationController
  protect_from_forgery
  layout "pages"

  def index
  end

  def products
  end

  def company
    @enable_sub_menu = true
  end

  def support
  end

  def login
  end
end

routes file:

App::Application.routes.draw do

  root :to => 'pages#index'

  ##Product / Search Routing
  match "products" => "pages#products"
  match "products/search" => 'pages#products/search'
  match "products/search/pricing" => 'pages#products/search/pricing'
  match "products/business/pricing" => 'pages#products/business/pricing'
  match "products/business" => 'pages#products/business'


  ##Company Pages Routing
  match "company/team" => 'pages#company/team'
  match "company/contact" => 'pages#company/contact'
  match "company" => 'pages#company'
  match "company/friends" => 'pages#company/friends'

  ##Support Routes
  match "support" => 'pages#suppprt'


  ##Login Routes
  match "login" => 'pages#login'
end

What I am trying to do is on any page the is /company I want to render a partial but on no others to do this I am using this

<%= render :partial => "pages/partials/sub_nav"  if @enable_sub_menu %>

Which looks in the controller method and checks to see if it should load the sub_nav partial

It works great for /company but it does not work for sub pages of /company such as /company/team

How can I enable it to load for all sub pages of the method company in the controller?

Upvotes: 2

Views: 2236

Answers (1)

engineerDave
engineerDave

Reputation: 3935

There is a helper method in your views called controller_name ActionController::Metal

This would probably allow you to trigger the partial based upon the controller you're in.

<%= render :partial => "pages/partials/sub_nav"  if controller_name == "company" %>

Note there is also a helper called action_name that allows you to check against the current action too. So you could combine them.

<%= render :partial => "pages/partials/sub_nav"  if controller_name == "company" || action_name == "company %>

Of course you'll probably want to roll this if statement up into a helper method in your ApplicationHelper to DRY up your view

Upvotes: 4

Related Questions