Passing parameters to erb view

Fábio Perez picture Fábio Perez · Jul 18, 2011 · Viewed 40.9k times · Source

I'm trying to pass parameters to an erb view using Ruby and Sinatra.

For example, I can do:

get '/hello/:name' do
  "Hello #{params[:name]}!"
end

How do I pass :name to the view?

get '/hello/:name' do
  erb :hello
end

And how do I read the parameters inside view/hello.erb?

Thanks!

Answer

Pavel Veller picture Pavel Veller · Jul 19, 2011

just pass the :locals to the erb() in your routes:

get '/hello/:name' do
    erb :hello, :locals => {:name => params[:name]}
end

and then just use it in the views/hello.erb:

Hello <%= name %>

(tested on sinatra 1.2.6)