1. 程式人生 > >tornado 靜態檔案路徑繫結細節

tornado 靜態檔案路徑繫結細節

先上web模組專案結構圖:
專案樹形圖


首先要將/static(注意,只能以static,不能帶s)和/templates資料夾繫結到tornado.web.Application當中,這樣才能讓伺服器載入渲染html、css、JavaScript等專案檔案,具體實現程式碼如下:

	def make_app():
		setting = dict(
        	template_path=os.path.join(os.path.dirname(__file__), "templates"),
        	static_path=os.path.join(os.path.dirname(__file__), "static"),
    	)
    	return tornado.web.Application([(r'/Demo', DemoHandler),
                                    ],
                                   **setting
                                   )

然後修改html當中對css、js檔案的引入方式,一定要多加一對引號啊!!!

以bootstrap.min.css檔案為例
錯誤寫法示例:

  • <link rel="stylesheet" type="text/css" href="{{static_url(css/bootstrap.min.css)}}">
    這裡很容易忽略,因為當你寫成下面這種形式:

  • <link rel="stylesheet" type="text/css" href="{{"static_url(css/bootstrap.min.css"}}">
    IDE會提示錯誤(實際也沒錯),所以建議最好用’和"交替的形式,如下:

  • <link rel="stylesheet" type="text/css" href="{{static_url('css/bootstrap.min.css')}}">


後來想想,覺得我這種錯誤很低階,如果把static_url當作方法,傳入的變數本來就不能直接以bootstrap.min.css這種直接傳,好歹變成字串吧…用單引號和雙引號都算。
既然花了我這麼久才發現這個問題,有必要記錄一下!