3

だから私は Sinatra (非常に基本) を使用することを学んでおり、次の基本的なコードを理解しています:

get '/derp' do
    haml :derp
end

私はすぐに次のように考えました: 十数ページある場合、上記のように URL ごとに get/do ステートメントを書かなければならないのでしょうか? 変数を使用して次のようなことを行う方法が必要です。

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

どこ$varに入力しますか。基本的/fooに、アドレスバーに入力すると、Sinatra が呼び出されたビューを探してfoo.haml使用するか、404 を表示し/barます/derp

それは可能ですか?これがどのように機能するかの基本的な側面を誤解していますか?学習を続けている間はこの質問を無視して、後で戻ってくる必要がありますか?

生活を楽にする本当に基本的な単純なことのように思えますが、人々が各ページを手動で宣言しているとは想像できません...

4

2 に答える 2

4

あなたはこれを行うことができます:

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

:allroutesが何であれ、hamlテンプレートが表示されます。たとえば、を押すとlocalhost/test、下にテンプレートが表示testされます。このためのはるかに単純なバージョンは、sinatraによって提供されるすべてのルートに一致を使用することです。

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.
于 2012-07-25T05:31:14.330 に答える