无法从gohtml文件中获取字段的数据。

huangapple go评论86阅读模式
英文:

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 != &quot;POST&quot; {
		http.Redirect(w, r, &quot;/&quot;, http.StatusSeeOther)
		return
	}

	userName := r.FormValue(&quot;user&quot;)
	userPronouns := r.FormValue(&quot;pronouns&quot;)

	d := struct {
		hostName     string
		hostPronouns string
	}{
		hostName:     userName,
		hostPronouns: userPronouns,
	}

	tpl.ExecuteTemplate(w, &quot;processor.gohtml&quot;, 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.

&lt;body&gt;
    &lt;h1&gt;BALLS&lt;/h1&gt;
    &lt;h2&gt; {{.hostName}} &lt;/h2&gt;
&lt;/body&gt;

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
}

huangapple
  • 本文由 发表于 2022年8月24日 14:03:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73468131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定