Apart from being a good idea or not, I would like to know how to access the :locals hash from inside a partial instead of the local variables with the same name?
I'm attempting to try to explore a potentially more efficient approach to a pattern I often find myself in involving default partial values:
:locals => { :opts => {:myvar => @myvar}}
Then inside partial:
opts.reverse_merge!(defaults)
It would be a lot cleaner to write (especially when opts get more numerous):
:locals => { :myvar => @myvar}
Then inside partial:
opts => defaults.merge(local_hash)
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.
Local variables are a specific type of variable that are only available within the context of a particular expression and can only be accessed within the function that defines them. Local variables are useful when you only need that data within a particular expression.
You can access everything that came in on the locals
hash to a rendered partial by calling local_assigns
. I think you'll find, however, that there is more coming in than you'd expect (as Rails creates a few local assigns of its own for your convenience). So your approach may need to adjust... but this is how you'd do it.
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