當試圖將值傳入.html
代碼時,我使用的是html/template
包。如何在Go中使用HTML/TEMPLATE包時設置不同的內容類型
但是,我似乎無法設置我的.html
文件中引用的.css
內容類型。它被作爲純文本提供給瀏覽器,因此格式被忽略。
在靜態的.html
文件中,我可以使用內置的http.Fileserver
,它負責處理內容類型,但是模板不起作用。我無法傳入變量。它只是顯示爲{{.}}
有沒有辦法給content-type
方便的內置文件服務器http.Fileserver
用的http.HandleFunc
模板的能力結合起來?
這是我的代碼,因爲它沒有使用http.Fileserver
。請注意,我Go
文件在啓動目錄和index.html
和.css
文件是一個子目錄/hello/
:
package main
import (
"html/template"
"io/ioutil"
"log"
"net/http"
)
var Message string = "test page"
func servePipe(w http.ResponseWriter, req *http.Request) {
dat, err := ioutil.ReadFile("hello/index.html")
if err != nil {
log.Fatal("couldn't read file:", err)
}
templ, err := template.New("Test").Parse(string(dat))
if err != nil {
log.Fatal("couldn't parse page:", err)
}
templ.Execute(w, Message)
}
func main() {
http.HandleFunc("/hello/", servePipe)
http.ListenAndServe(":8080", nil)
}
這是我.html
文件。 html頁面沒有任何問題。這是獨立的.css
文件沒有被提供(鏈接在.html
文件中),因此格式不會發生。
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p>{{.}}</p>
</body>
</html>
謝謝!這非常翔實!我現在手動單獨地爲我的.css樣式表提供服務(現在它可以工作!),但是我正在閱讀規範中的ParseFiles和ParseGlob,以便按照您的建議進行優雅地操作。 – nosequeldeebee
感謝您也指出需要避免解析我的處理程序。我會審查。 – nosequeldeebee