<%= render :partial => 'partial/path', :locals => {:xyz => 'abc'} %>
vs
<%= render :partial => 'partial/path', :object => @some_object %>
I think the first one make a local variable named xyz
available in the partial and the second one makes a local variable named object
available in the partial. So what is the difference? (Besides locals
allows more than one variable)
Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
Ruby on Rails Views Partials Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.
local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not. Here you render a partial with some values, the headline and person will become accessible with predefined value.
By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.
The second form
render :partial => 'account', :object => @some_account
will make sure the account
variable in the partial will be set to @some_account
. You can rename the variable using the :as
option.
The biggest advantage of the :locals
is that
So you could do something like
render partial => 'some_view', :locals => { :user => account.user, :details => some_details_we_retrieved }
making a clear seperation possible when needed.
The disadvantage of the :locals
approach is that it is more verbose, and sometimes a simple
render :partial => 'account'
is identical to
render :partial => 'account', :locals => {:account => @account }
So use the one which suits you the best (or where it suits the best).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With