Example analysis of Go multivalued substitution templates
- 2020-05-19 05:00:19
- OfStack
This article analyzes the use of HTML templates for multivalued substitution in the Go language. Share with you for your reference. The details are as follows:
There are two ways to provide mutable value substitution based on the HTML template. Appends an example of an array iteration.
Pass map to implement multi-value substitution
package main
import (
"html/template"
"os"
)
func main() {
t, _ := template.New("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args1 := map[string]string {"Username": "Hypermind", "MainPage": "http://hypermind.com.cn/go"}
_ = t.ExecuteTemplate(os.Stdout, "T", args1)
}
Pass in a custom structure to implement multivalue substitution
package main
import (
"html/template"
"os"
)
type Info struct{
Username string
MainPage string
}
func main() {
t, _ := template.New("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args2 := Info{Username: "Hypermind", MainPage: "http://hypermind.com.cn/go"}
_ = t.ExecuteTemplate(os.Stdout, "T", args2)
}
Iterative display of a 2-dimensional array
package main
import (
"html/template"
"os"
)
type Matrix struct {
Array [9][9]int
}
func main() {
tmpl, _ := template.New("example").Parse(`
{{ $a := .Array }}
{{ range $a }}{{ $elem := . }}|{{ range $elem }}{{ printf "%d" . }}{{ end}}|
{{end}}`)
tmpl.Execute(os.Stdout, matrix)
}
I hope this article has been helpful to your programming of Go language.