Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the :locals hash from inside a partial instead of the local variables with the same name?

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)
like image 958
pixelearth Avatar asked Aug 19 '14 19:08

pixelearth


People also ask

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.

What is true about local variables?

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.


1 Answers

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.

like image 98
pdobb Avatar answered Sep 30 '22 14:09

pdobb