ruby-on-railsrender

What's :locals for in render in rails?


Here is the API definition for render:

render(options = {}, locals = {}, &block)

Returns the result of a render that’s dictated by the options hash. The primary options are:

    :partial - See ActionView::Partials.

    :file - Renders an explicit template file (this used to be the old default), add :locals to pass in those.

    :inline - Renders an inline template similar to how it’s done in the controller.

    :text - Renders the text passed in out.

There is no explanation about what's the purpose of locals here? What's locals for?


Solution

  • For example:

    1. <%= render :partial => "account" %>

      This means there is already an instance variable called @account for the partial and you pass it to the partial.

    2. <%= render :partial => "account", :locals => { :account => @buyer } %>

      This means you pass a local instance variable called @buyer to the account partial and the variable in the account partial is called @account. I.e., the hash { :account => @buyer } for :locals is just used for passing the local variable to the partial. You can also use the keyword as in the same way:

      <%= render :partial => "contract", :as => :agreement

      which is the same as:

      <%= render :partial => "contract", :locals => { :agreement => @contract }