2016年3月15日 星期二

使用rails產生靜態網頁(三):用變數來統一處理大量不一樣的分頁

這一回我們要解決當特定的template不存在時,產生的error。

處理的機制就是在controller中,判 斷params[:single_page]這個內含分頁名稱的變數,是否有對應的template存在,如果有,則render該template,若否,則統一導向一個指示網址錯誤的提醒網頁。


controller改寫為
class PagesController < ApplicationController
 def show if valid_page?
       render template: "pages/#{params[:single_page]}"
 else render file: "public/404.html", status: :not_found end end private

 def valid_page?
       File.exist?(Pathname.new(Rails.root + "app/views/pages/#{params[:single_page]}.html.erb")) end

 end

值得一提的是,ruby要完成一件事有許多種作法,在這裡render template的方式是
render template:"page#{params[:single_page]}" 將path作為值傳給template這個變數,另外還有一個作法是
render params[:single_page] 這樣也可以達到一樣的作法喔,而且看起來乾淨多了。