Html template use on golang

2019-09-29 04:23发布

问题:

Sorry im beginner and i read golang.docs but didnt understand well. i`ve : index.html:

<html>
<head>
</head>
<body>
<form action type="checkbox" name="test" value="A" {{.checked}}>
<input type="submit" value="save">
</body>
</html>

in main.go if user click save button then check checkbox redirect that page and show checkbox checked

回答1:

You could send variables in map. For example:

package main

import (
    "bytes"
    "fmt"
    "text/template"
)

func main() {
    t, _ := template.New("hi").Parse("Hi {{.name}}")
    var doc bytes.Buffer
    t.Execute(&doc, map[string]string{"name": "Peter"})
    fmt.Println(doc.String()) //Hi Peter
}


回答2:

The . is defined in go code.

Please provide the snippet of your go code where the template is executed, something like the following codes:

    t, _ := template.ParseFiles(tmpl + ".html")
    t.Execute(w, data) // the data must feature the field "checked"

Or

    templates.ExecuteTemplate(w, tmpl+".html", data) // the data must feature the field "checked"

You can pass any type(interface{}) to a functions that execute a template as "data". Usually it is a Struct or a Map[string]string.

How to set the checked Probably the "checked" is setted in the main.go at handler according to the posted form.

Read the docs and explain it better. Please