Rails: Should partials be aware of instance variables?

前端 未结 4 1181
渐次进展
渐次进展 2020-12-07 13:05

Ryan Bates\' nifty_scaffolding, for example, does this

edit.html.erb

<%= render :partial => \'form\' %>

new.html.erb

4条回答
  •  时光说笑
    2020-12-07 13:38

    In recent versions of Rails it is quite a bit easier to render partials and pass locals to them. Instead of this.

    <%= render :partial => 'form', :locals => { :item => @item } %>
    

    You can do this.

    <%= render 'form', :item => @item %>
    

    I don't do this in the Nifty Scaffold generator to keep backwards compatibility, but I'll change this in a future release.

    As for whether it's acceptable to use instance variables in partials. I think it is. In all practicality, what is the downside? Certainly things can get out of hand if you aren't consistent, but I like to apply these guidelines.

    1. Never create an instance variable just to share it between partials. Usually this means you will only be sharing the controller resource object.

    2. If the partial is the same name as the resource, pass it as a local with <%= render @item %>.

    3. If the partial will be shared across multiple controllers then only use locals.

    This is what works well for me anyway.

    Bonus tip: if you find yourself passing in a lot of locals into a partial and you want some of them to be optional, create a helper method which renders the partial. Then always go through the helper method so you can make a clean interface with optional args for rendering the partial.

提交回复
热议问题