Html template use on golang

2019-09-29 04:31发布

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

2条回答
做个烂人
2楼-- · 2019-09-29 04:48

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
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-09-29 05:08

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

查看更多
登录 后发表回答