Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you only use local variables in a partial?

Using local variables seems advisable in a partial that could be used application-wide to avoid dependencies across the application.

But within a single controller it seems acceptable to reference instance variables that you know will be available in all of the actions that use the partial.

If you do this, there seems to be a risk, however, that a particular action may get changed to no longer provide the instance variable to its view. Then the partial would stop working. I'm not sure if this is really a problem, though, since a regular view would encounter the same risk.

Does it matter if you reference instance variables in a partial?

like image 499
eggdrop Avatar asked May 26 '09 01:05

eggdrop


2 Answers

You're on a roll today! :-)

You can pass variables into the partial as :locals to keep this all nice and clean. For example,

render :partial => 'my_partial', :locals => { :some_variable => some_variable, :some_important_value => 'an important point!' }

These variables are then available in the partial view:

<%= some_variable %>
<%= some_important_value %>

However, there is nothing specifically wrong with using instance variables in your partials.

like image 137
Tim Sullivan Avatar answered Nov 01 '22 03:11

Tim Sullivan


i would only recommend using instance variables as long as the partial is not shared, since this can get confusing very fast ;)

like image 27
grosser Avatar answered Nov 01 '22 04:11

grosser