Conditional in Rails partial depending on the context page?

送分小仙女□ 提交于 2020-01-04 08:23:27

问题


I was wondering if I could execute / display some stuff differently in partials depending on the context in which it appears.

For example, I have a _user_info partial that appears in a sidebar, and also in the user page, and I want to display some extra info in the second case. How can I express that kind of conditions?


回答1:


What you're asking for is something this:

if params[:controller].eql?('users')
  view code

However I would split the partial into two separate partials and display the distinct parts from whichever view you need.




回答2:


You can use controller_name and action_name methods.

if controller_name == 'user' && action_name == 'show'
  details
end



回答3:


Sure, it just depends on how you want to discover/expose that context. The simple way is conditionals, which can be set in any number of ways, or derived from a set of conditions. That can happen in a filter, an action, etc.

If the changes are large enough, better to just encapsulate them in separate partials.

Another option is to wrap the render tag in a helper that calculates/grabs those conditions.

It kind of depends on the nature of the conditions, where/how you want to deal with them, etc.




回答4:


Or pass a variable into the partial via :locals =>



来源:https://stackoverflow.com/questions/7455215/conditional-in-rails-partial-depending-on-the-context-page

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