2016年3月22日 星期二

使用rails產生靜態網頁(四):加入超連結

使用rails產生靜態網頁(四):加入超連結

這一回我們要介紹的是如何在pages/test這個分頁中使用超連結連結到pages/index 這個分頁。

方法很簡單,就是在template中使用helper。所謂的helper是指在template中將資料轉換成html字串。在我們的例子中,link_to這個helper就是要產生一個超連結的html字串(i.e. <a href...(略)...>)。所謂的資料是"index"這個字串,這個字串包含了我們想要去的分頁名稱。而helper是一個函式,我們不用輸入繁雜的html,將資料作為函式的輸入,就可以產生繁雜的html。

而在這裡我們也自訂了一個函式to_page(),可以回傳完整分頁的path

app/views/pages/test.html.erb
<%= link_to "index", to_page("index") %>

vim app/helpers/pages_helper.rb (註:在產生pages controllers時,這個pages_helper.rb 自動產生)
def to_page(specific_page)
   return "http://localhost:3000/pages/#{specific_page}"
end


補充:使用named routes設定的方式,不需要自定helper,只要在config/routes.rb中修改,即可以有helper 使用:

config/routes.rb
get 'pages/:single_page' => 'pages#show', :as=> 'page'

則views中則可以改為
<%= link_to "index", page_path("index") %>

說明:named routes 命名路由,可以幫助我們產生URL helper :as=page,rails就會產生一個page_path(相對路徑,一般較常用),以及path_url(絕對路徑,特定情況下需要,比如email application) 的 URL helper