Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

ruby on rails - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...