Html template not working on POST

whatarethose.go file

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)

func handler(w http.ResponseWriter, r *http.Request) {
    // request switch
    switch r.Method {
    case "GET":     
        http.ServeFile(w, r, "whatarethose.html")
    case "POST":
            // send name and value to html
	    t, err := template.ParseFiles("whatarethose.html")

	        if err != nil {

		items := struct {
			Name string
			Value float64
			Name: "hi",
			Value: 0.1,

		t.Execute(w, items)

whatarethose.html file

            <form name="predict" method="POST" action="/" target="hiddenFrame">
                <div class="row half">
                    <div class="6u">
                    <input type="text" id="url" class="text" name="url" placeholder="URL"></textarea>
                <div class="row">
                    <div class="12u">
                        <button id="submit" class="button">Submit</button>

            <div id="result">
              <img id="loader" style="display:none" src="/images/load.gif"></div>
              <div id="res">
                <p id="info">{{.Name}}<br>{{.Value}}</p>
                <img id="demo" src="">

Above, some skeleton code from my project. I have a form on my web page which makes a POST request on submit. In my go code, I am trying to pass the response from an API call as a struct back to the html page to display here: <p id="info">{{.Name}}<br>{{.Value}}</p>. The only thing that displays are the literal strings {{.Name}} and {{.Value}}. However, when I move my template code in my go file to or before the GET case, it works with any value, but I don’t have the values returned from the API call, so I need to have the template code in my POST case but it’s not working. I’d really appreciate it if someone could tell me why this is and how I could go about resolving it? Thank you.

It seems like a couple of things are missing here. The following modifications work for me with your example:

  • In whatarethose.go, replace t.Execute() with t.ExecuteTemplate(). Eg: t.ExecuteTemplate(w, "whatarethose", items)

  • In whatarethose.html, add a {{define}} to access your data. Eg:

        {{define "whatarethose"}}
        <p id="info">{{.Name}}<br>{{.Value}}</p>
        <img id="demo" src="">
        {{ end }}

Edit: Also I just realized this post is a month old and probably not even relevant anymore. Sorry!

1 Like