Passing parameters to erb view

2020-02-18 04:12发布

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!

标签: ruby sinatra erb
3条回答
对你真心纯属浪费
2楼-- · 2020-02-18 04:49

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

查看更多
3楼-- · 2020-02-18 04:54

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)

查看更多
家丑人穷心不美
4楼-- · 2020-02-18 05:05
get '/hello/:name' do
  "Hello #{params[:name]}!"
end

You cannot do this in routes.

You want to set the params in the controller.

app/controllers/some_controller.rb

def index
    params[:name] = "Codeglot"
    params[:name] = "iPhone"    
    params[:name] = "Mac Book"      
end

app/views/index.html.erb

<%= params[:name] %>
<%= params[:phone] %>
<%= params[:computer] %>
查看更多
登录 后发表回答