【发布时间】:2020-03-22 18:34:29
【问题描述】:
尝试将变量数据的内容打印到 html 页面中:
package main
import (
"net/http"
"fmt"
"log"
"html/template"
)
var tpl *template.Template
func init(){
tpl= template.Must(template.ParseGlob("*.html"))
}
func main(){
http.HandleFunc("/", index)
http.HandleFunc("/process", processor)
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request){
tpl.ExecuteTemplate(w, "index.html",nil)
}
func processor(w http.ResponseWriter, r *http.Request){
if r.Method != "GET" {
http.Redirect(w,r,"/", http.StatusSeeOther)
return
}
data := r.FormValue("data")
fmt.Printf("%s",data)
err:=tpl.ExecuteTemplate(w, "processor.html", string(data))
if err != nil {
log.Fatalf("execution failed: %s", err)
}
//tpl.ExecuteTemplate(w, "processor.html",data)
}
这是html
<html>
<head>
<title>PROCESSOR</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>{{.data}}</h1>
</body>
</html>
这是我的 shell 打印出来的:
poo2020/03/22 19:13:50 execution failed: template: processor.html:8:11: executing "processor.html" at <.data>: can't evaluate field data in type string
exit status 1
便便是数据的内容(证明我从初始 html 页面正确获取它。 检查了一些类似的问题,尝试使用变量 $data,但我遇到了同样的问题。
【问题讨论】: