Home > Net >  Can't get data from field in gohtml file
Can't get data from field in gohtml file

Time:08-24

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.

CodePudding user response:

struct fields have to be exported to be available in templates.
Change your struct to

d := struct {
  HostName     string
  HostPronouns string
}
  • Related