Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to erb view

Tags:

ruby

erb

sinatra

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!

like image 386
Fábio Perez Avatar asked Jul 18 '11 18:07

Fábio Perez


2 Answers

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)

like image 183
Pavel Veller Avatar answered Sep 21 '22 23:09

Pavel Veller


Not sure if this is the best way, but it worked:

get '/hello/:name' do
  @name = params[:name]
  erb :hello
end

Then, I can access :name in hello.erb using the variable @name

like image 26
Fábio Perez Avatar answered Sep 21 '22 23:09

Fábio Perez