Go html/template ExecuteTemplate 方法设置 HTML 后缀访问
可以通过在模板文件名中添加'.html'后缀来让Go的html/template的ExecuteTemplate方法识别模板文件的后缀为html。例如,如果模板文件名为'template.html',则可以使用以下代码来执行模板:
package main
import (
"html/template"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("template.html"))
tmpl.ExecuteTemplate(w, "template.html", nil)
})
http.ListenAndServe(":8080", nil)
}
在此示例中,我们将模板文件名设置为'template.html',并在使用ExecuteTemplate方法时将模板名称也设置为'template.html'。这样,执行模板时就可以自动识别模板文件的后缀为html。
原文地址: https://www.cveoy.top/t/topic/nSCI 著作权归作者所有。请勿转载和采集!