Tuesday, May 3, 2011

How to display content that differs across controllers and methods in application layout?

I'm trying to display a javascript feedback widget in my default application.rhtml in a rails app. It will only appear on a subset of pages, distributed across different controllers.

Trying to figure out the best way to do this.

One thought was to do something like this:

<%= render :partial => "layouts/feedback_tab"  if @show_feedback_tab == true %>

and then setting @show_feedback_tab in every method in every controller. this seems overly complex. my second thought was that i could default @show_feedback_tab to true and set it to false for the relevant individual methods where i don't want to show it. but a global var doesn't seem right, and a method in application_controller won't work (i think) as the display is dependent on the method that's being called.

Any thoughts?

From stackoverflow
  • You can write method in application_controller.rb:

    def show_feedback_tab?
      if params[:controller] == :user && params[:action] == :index
        return true
      end
      ...
      or put here any other logic
      ...
      false
    end
    

    and add it as a helper method (in application_controller.rb):

    helper_method :show_feedback_tab?
    

    then you can use it in views like this:

    <%= render :partial => "layouts/feedback_tab"  if show_feedback_tab? %>
    
    kareem : perfect, thanks!

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.