The example in this article describes the Go language template usage. Share to everyone for your reference. The specific analysis is as follows:
Golang's template package is very easy to use, do some complex text format generation is very helpful, the generation of Web pages is also very good, very convenient.
Copy Code code as follows:
Package Main
Import (
"FMT"
"OS"
"Text/template"
)
Type latlng struct {
Lat float32
Lng float32
}
Func (latlng latlng) string () string {
Return FMT. Sprintf ("%g/%g", latlng. Lat, latlng. Lng)
}
Func Main () {
Data: = []template. funcmap{}
data = append (data, template. funcmap{"name": "Dotcoo1", "url": "http://www.jb51.net/", "latlng": latlng{24.1, 135.1}})
data = append (data, template. funcmap{"name": "Dotcoo2", "url": "http://www.jb51.net/", "latlng": latlng{24.2, 135.2}})
data = append (data, template. funcmap{"name": "Dotcoo2", "url": "http://www.jb51.net/", "latlng": latlng{24.3, 135.3}})
DATATPL: = ' {{range.}} {{Template ' user '.}} {{End}} '
USERTPL: = ' {{define ' user '}}name:{{.name}}, Url:{{.url}}, latlng:{{.latlng}} lat:{{.latlng. Lat}} lng:{{.latlng. Lng}}
{{End}} '
TPL, err: = template. New ("Data"). Parse (DATATPL)
If Err!= nil {
Panic (ERR)
}
_, Err = TPL. Parse (USERTPL)
If Err!= nil {
Panic (ERR)
}
Err = TPL. Execute (OS. Stdout, data)
If Err!= nil {
Panic (ERR)
}
println ()
}
I hope this article will help you with your go language program.