Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render partial :object vs :locals

<%= 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)

like image 438
Chris Muench Avatar asked Feb 25 '11 20:02

Chris Muench


People also ask

How do you render partials?

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() .

What are partials Ruby?

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.

What is Local_assigns?

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.

How can you tell Rails to render without a layout *?

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.


1 Answers

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

  • you have very clear control over the objects and names
  • you can assign more than 1 variable

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).

like image 91
nathanvda Avatar answered Oct 07 '22 11:10

nathanvda