英文:
Can't get data from field in gohtml file
问题
我正在尝试构建一个非常基本的页面,该页面从表单中获取用户输入,并在HTML模板中显示出来。
以下是应该从表单中获取输入数据并将其作为变量在模板中使用的代码。为了进行调试,输入数据会打印到控制台中,确保它在那里显示正确。
func processor(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
userName := r.FormValue("user")
userPronouns := r.FormValue("pronouns")
d := struct {
hostName string
hostPronouns string
}{
hostName: userName,
hostPronouns: userPronouns,
}
tpl.ExecuteTemplate(w, "processor.gohtml", d)
fmt.Println(d.hostName)
fmt.Println(d.hostPronouns)
}
以下是应该显示表单中部分信息的HTML代码。最终它会变得更加复杂,但现在我只需要它能工作。
<body>
<h1>BALLS</h1>
<h2> {{.hostName}} </h2>
</body>
我无法弄清楚为什么数据没有显示出来。如果我将{{.hostName}}
更改为{{.}}
,表单中的所有数据都会显示出来,所以数据确实被传递了。
英文:
I'm trying to build a very basic page that takes user input from a form and displays it within an html template
Here's the code that should take the input data from a form and make it available as a variable in the template. The input is printed to console for sanity check, it does show correctly in there.
func processor(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
userName := r.FormValue("user")
userPronouns := r.FormValue("pronouns")
d := struct {
hostName string
hostPronouns string
}{
hostName: userName,
hostPronouns: userPronouns,
}
tpl.ExecuteTemplate(w, "processor.gohtml", d)
fmt.Println(d.hostName)
fmt.Println(d.hostPronouns)
}
Here is the html code that should display part of the information from the form. Eventually it's going to be more complicated but for now I just need it to work.
<body>
<h1>BALLS</h1>
<h2> {{.hostName}} </h2>
</body>
I can't figure out why the data doesn't show up. If I change the {{.hostName}}
for {{.}}
all the data from the form is there, so it is going through.
答案1
得分: 0
结构字段必须导出才能在模板中使用。将您的结构更改为:
d := struct {
HostName string
HostPronouns string
}
英文:
struct fields have to be exported to be available in templates.
Change your struct to
d := struct {
HostName string
HostPronouns string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论