2012年9月7日 星期五

[GoLang]如何在Google App Engine上使用template……

搜尋半天才找到這東西的用法……超麻煩……

下為我的project的檔案內容:
|-----app.yaml
+-----hello
      |-----hello.go
+-----js
      |-----test.js
|-----test.html(這個就是我的模板檔……)

靠著全知全能的好朋友--Google竟然找不到最好地結果……
Google找到最能當參考資料的有:google app engine - Go, AppEngine: How to structure templates for application - Stack Overflow(太複雜,所以根本不想看……)和Cuddle(不過裡面的教學code……不知道是不是因為沒有寫出import的部份……不能使用)
最後我竟然是靠著Google App Engine附的Demo來學會的……

首先當然是寫模板的內容……
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Test</h1>
<span>Template works successfully.</span>
</body>
</html>

然後編寫hello.go……
package hello
import (
"fmt"
"net/http"
"html/template"
)
func hello(w http.ResponseWriter, r *http.Request) {
templates := template.Must(template.ParseFiles("test.html"))
templates.ExecuteTemplate(w, "test.html", nil)
}
func init() {
http.HandleFunc("/", hello)
}

上面的code是參考google_appengine/demos/moustachio的……
是說……我嘗試要再開一個templates的資料夾來放templates的檔案可是會失敗……另外就是js檔……要記得另外寫個http.HandleFunc來讀取……
追加
其實後來發現,可以從 golang 的 html/template class 找到資料的說

沒有留言:

張貼留言