Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters from a controller to a template?

It seems that setting multiple instance variables in a controller's action (method) causes problems in the template, only the very first instance variable got passed to the template. Is there any way to pass multiple variables to the template? Thanks! And why, in Ruby's perspective, does the template get access to the instance variables in an action?

like image 301
freenight Avatar asked Dec 22 '09 04:12

freenight


2 Answers

You might also want to look into the :locals option of render. Which accepts a hash such that keys are symbols that map to local variable names in your template, and the values are the values to set those local variables to.

Example:

render "show", :locals => {:user => User.first, :some_other_variable => "Value"}

and this template

User ID: <%= user.id %><br>
Some Other Variable: <%=some_other_variable%>

will produce:

User ID: 1<br>
Some Other Variable: Value

When you're reusing partials across multiple controllers. Setting local variables with the :locals option is simpler and much more DRY than using instance variables.

like image 91
EmFi Avatar answered Oct 17 '22 06:10

EmFi


you shouldn't have any problem setting multiple instance variables. For example:

class CarsController < ApplicationController
  def show
    @car = Car.find(:first)

    @category = Category.find(:first)
  end
end

will allow you to access both @car and @category in cars/show.html.erb

The reason this works is nothing inherent to ruby, but some magic built into rails. Rails automatically makes any instance variable set in a controller action available to the corresponding view.

like image 20
Seth Archer Brown Avatar answered Oct 17 '22 06:10

Seth Archer Brown