13

I have a partial that I am using in different pages. I want to conditionally hide a certain div inside the partial based on the view that is rendering it.

I was thinking about creating a page specific javascript file that would look up the div and and hide it.

But, if there was a way to retrieve the view name / page name inside the partial it would be central to the partial and would not necessitate loading the same javascript file in multiple pages.

Does anybody know a way to do this inside a partial

4 Answers 4

19

While @wahaj's answer would work, if you want to do what you need in a central location, you could check the controller_name and action_name variables in the partial to determine the view you're in (e.g. controller_name == "services" and action_name == "show" would let you know you're in the Show view for the Service controller)

7
  • 6
    params[:controller] or params[:action] are not recommended, instead use 'controller_name','action_name'
    – Naveed
    Jan 13, 2012 at 8:31
  • 1
    Wow, I feel like an idiot. Didn't even know that existed. Thanks for pointing that out!
    – jhdavids8
    Jan 13, 2012 at 16:32
  • 1
    You'd better edit your original answer to reflect this then, or people may do what you said originally. May 8, 2013 at 17:29
  • 1
    @Naveed can elaborate on why it's not recommended? Jul 31, 2014 at 16:43
  • 1
    @adamwong246 well we params is a hash and we can change its values( params[:controller]='blakh') yep why would anyone change values for :controller, :action but still humans are errors pron. controller_name is safe to use.
    – Naveed
    Aug 3, 2014 at 23:42
6

you can get the name of the currently-rendering partial from within a Helper method with the following :

controller.view_context.view_renderer.instance_variable_get('@_partial_renderer').instance_values['path']
2

You could send the style parameter as a local variable to the partial, varying the parameter depending on where you're calling from. Something like:

render :partial => 'xyz', :locals => {:style => 'display:none or display:block'}

and in the partial you could do:

<div style=<%=style%>></div>
1
  • 1
    or perhaps a local var 'hide_div'. A nicety with partials is the defined? method, which means the variable would not be required on all calls to render the partial. Jan 13, 2012 at 6:04
1

simple solution , inside your partial check if you need to show partial or not

_partial_name.html.erb

<%= content_tag :div, :style=> "display : #{show_div? ? 'block' : 'none'}" do%>
  html...or other stuff
 <%end%>

and then in application helper

app/helper/application_helper.rb

def show_div? #you can set name of your div like 'show_sidebar_div?'
  #decide either show this div or not
 action_name == 'show'
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.