gpt4 book ai didi

ruby - 在 Sinatra 中,我可以在路由和 View 中使用变量吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:53 25 4
gpt4 key购买 nike

所以我正在学习使用 Sinatra(非常基础)并且我了解以下基本代码:

get '/derp' do
haml :derp
end

我很快开始思考:如果我有十几页,我是否必须像上面那样为每个 url 编写一个 get/do 语句?必须有一种方法可以使用变量来做这样的事情:

get '/$var' do
haml :$var
end

其中 $var 是我输入的任何内容。基本上,如果我在地址栏中输入 /foo,我希望 Sinatra 查找名为 foo 的 View 。 haml 并使用它,否则显示 404。/bar/derp 等也是如此。

这可能吗?我是否误解了它应该如何工作的一些基本方面 - 我是否应该在继续学习的同时忽略这个问题并稍后再回来?

这似乎是一件非常基本的简单事情,可以让生活更轻松,我无法想象人们手动声明每个页面......

最佳答案

你可以这样做:

get '/:allroutes' do
haml param[:allroutes].to_sym
end

这将显示 :allroutes 的 haml 模板。例如,如果您点击 localhost/test,它将在 test 下显示模板,依此类推。更简单的版本是使用 sinatra 提供的 match all 路由:

get '/*/test' do
# The * value can be accessed by using params[:splat]
# assuming you accessed the address localhost/foo/test, the values would be
# params[:splat] # => ['foo']
haml params[:splat][0].to_sym # This displays the splat.haml template.
end

get '/*/test/*/notest' do
# assuming you accessed the address localhost/foo/test/bar/notest
# params[:splat] # => ['foo', 'bar']
haml params[:splat][0].to_sym # etc etc...
end

# And now, all you need to do inside the blocks is to convert the variables into
# a symbol and pass in to haml to get that template.

关于ruby - 在 Sinatra 中,我可以在路由和 View 中使用变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11643174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com