我正在尝试学习Golang。我只想发送数据进行查看。但是数据没有到达main.gohtml。我不明白原因。如果我从define
中打印出数据,它将起作用。但是,如果要打印define "content"
中的数据(转到main.gohtml),则数据为空。define "title"
部分正在工作。我只是不能发送带有变量的数据。如果我删除{{.text}}
部分并写一些东西,它会起作用。
main.go文件
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("template/*.gohtml"))
}
func main() {
http.HandleFunc("/about", fabout)
http.ListenAndServe(":80", nil)
}
func fabout(w http.ResponseWriter, r *http.Request) {
values, isset := r.URL.Query()["text"]
var value string
if isset == true {
value = values[0]
} else {
value = ""
}
data := map[string]interface{}{
"text": value,
}
tpl.ExecuteTemplate(w, "about.gohtml", data)
}
about.gohtml
{{template "main"}}
{{define "title"}}About me{{end}} //this is working
{{define "content"}}{{.text}}{{end}} //this is not working
{{.text}} //this is working
main.gohtml
{{define "main"}}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{template "title"}}</title>
</head>
<body>
<ul>
<li><a href="">Page 1</a></li>
<li><a href="">Page 2</a></li>
<li><a href="">Page 3</a></li>
<li><a href="">Page 4</a></li>
<li><a href="">Page 5</a></li>
</ul>
<div style="padding:100px 0;">{{template "content"}}</div>
<footer>
this is footer
</footer>
</body>
</html>
{{end}}
最佳答案
调用模板时,您需要传递任何必要的数据。 docs的语法为:
因此,解决此问题的一种简单方法是在调用main时传递.
:{{template "main" .}
和调用内容时相同:{{template "content" .}}
最后,内容可以使用以下值:{{define "content"}}{{.text}}{{end}}
注意:使用参数.
传递所有数据;您还可以只将.text
传递到main
中(然后在调用.
时并在内容内(content
)使用{{.}}
。
有关简化的工作示例,请参见this playground。
关于go - 如何将数据发送到GoHTML模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62441436/