我在獲取"html/template"包以正確解析模板時遇到問題。我正在嘗試將 HTML 內容解析為我制作的模板頁面,但是,當我嘗試時,解析的頁面以轉義的 HTML 結束,而不是我想要的實際代碼。Go 文檔說我可以簡單地使用該HTML()函數將字符串轉換為 a type HTML,這被認為是安全的并且應該被解析為 HTML。我已經Content在我的type Pagea 中創建了我的字段template.HTML,它編譯得很好,但是當我template.HTML(content)在第 53 行中使用該函數時,我收到一個編譯器錯誤說:template.HTML undefined (type *"html/template".Template has no field or method HTML)使用HTML(content)(沒有前面的template.)會導致此錯誤:undefined: HTML我的最終目標是讓其他 HTML 文件解析index.html為 HTML 并被瀏覽器解釋為 HTML。任何幫助表示贊賞。package mainimport ( "fmt" "html/template" "io" "io/ioutil" "net/http" "regexp" "strings")func staticServe() { http.Handle( "/assets/", http.StripPrefix( "/assets/", http.FileServer(http.Dir("assets")), ), )}var validPath = regexp.MustCompile("^/(|maps|documents|residents|about|source)?/$")// This shit is messy. Clean it up.func servePage(res http.ResponseWriter, req *http.Request) { type Page struct { Title string Content template.HTML } pathCheck := validPath.FindStringSubmatch(req.URL.Path) path := pathCheck[1] fmt.Println(path) if path == "" { path = "home" } template, err := template.ParseFiles("index.html") if err != nil { fmt.Println(err) } contentByte, err := ioutil.ReadFile(path + ".html") if err != nil { fmt.Println(err) } content := string(contentByte) page := Page{strings.Title(path) + " - Tucker Hills Estates", template.HTML(content)} template.Execute(res, page)}// Seriously. Goddamn.func serveSource(res http.ResponseWriter, req *http.Request) { sourceByte, err := ioutil.ReadFile("server.go") if err != nil { fmt.Println(err) } source := string(sourceByte) io.WriteString(res, source)}func main() { go staticServe() http.HandleFunc("/", servePage) http.HandleFunc("/source/", serveSource) http.ListenAndServe(":9000", nil)}
- 2 回答
- 0 關注
- 440 瀏覽
添加回答
舉報
0/150
提交
取消