2012-07-25 32 views
3

所以我學習使用西納特拉(最基礎的),我瞭解以下基本代碼:在Sinatra中我可以在路線和視圖中使用變量嗎?

get '/derp' do 
    haml :derp 
end 

我很快就開始思考:如果我有十幾頁,我必須寫一個get /做每個網址的聲明,如上所述?必須有使用變量做這樣的事情的方式。

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

其中$var是什麼,我輸入基本上,如果我/foo在地址欄中鍵入我想西納特拉尋找一個觀點叫foo.haml和使用它,或者顯示404.與/bar,/derp等相同,等等。

這可能嗎?我是否誤解了本應該如何工作的一些基本方面 - 我是否應該在繼續學習並在以後再回來時忽略這個問題?

這似乎是一個很基本的簡單的事情,這將使生活更輕鬆,我無法想象人們手工申報的每一頁...

回答

4

你可以這樣做:

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

哪樣顯示任何haml模板:allroutes是。例如,如果您點擊localhost/test,它將顯示test等模板。這更簡單的版本是通過使用西納特拉提供的比賽所有路線:

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. 
+0

啊哈,謝謝!我花了一分鐘時間,但我想我明白現在發生了什麼。壞蛋。 – zakkain 2012-07-25 06:09:28

+0

由於這是一個數組,因此您需要像這樣指定索引:'params [:splat] [0]'輸出'foo'(String),然後可以將其轉換爲符號。我在第二個例子中犯了一個錯誤。感謝您的更正。 – Kashyap 2012-07-25 06:09:39

+0

這就是扔我,是的。謝謝你的幫助! – zakkain 2012-07-25 06:13:15

0

除了由卡什亞普的出色答卷。

如果你希望把你的參數並沒有讓他們出params哈希可以的:

get '/*/test/*/notest' do |first, second| 
    # assuming you accessed the address localhost/foo/test/bar/notest 
    # first => 'foo' 
    # second => 'bar' 
    haml first.to_sym # etc etc 
end 
相關問題