rails access view name inside partial

為{幸葍}努か 提交于 2019-12-21 07:55:59

问题


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


回答1:


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)




回答2:


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']



回答3:


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>



回答4:


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


来源:https://stackoverflow.com/questions/8846484/rails-access-view-name-inside-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!