亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 的“html/template”包中的 HTML() 函數有問題

Golang 的“html/template”包中的 HTML() 函數有問題

Go
慕容708150 2021-07-01 14:01:26
我在獲取"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 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

您正在使用名為 template 的變量隱藏您的包。最簡單的解決方法可能是將變量名稱更改為 tmpl 或其他名稱。


查看完整回答
反對 回復 2021-07-12
  • 2 回答
  • 0 關注
  • 440 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號