This article analyzes the usage of HTML templates for multiple-value replacement in Go language. Share it for your reference. The details are as follows:
Here are two ways to provide multivariate value replacement based on HTML templates. Also append an example of array iteration.
Passing in map to implement multi-value replacement
Copy the codeThe code is as follows:
package main
import (
"html/template"
"os"
)
func main() {
t, _ := ("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args1 := map[string]string {"Username": "Hypermind", "MainPage": "/go"}
_ = (, "T", args1)
}
import (
"html/template"
"os"
)
func main() {
t, _ := ("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args1 := map[string]string {"Username": "Hypermind", "MainPage": "/go"}
_ = (, "T", args1)
}
Passing in a custom structure to implement multi-value replacement
Copy the codeThe code is as follows:
package main
import (
"html/template"
"os"
)
type Info struct{
Username string
MainPage string
}
func main() {
t, _ := ("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args2 := Info{Username: "Hypermind", MainPage: "/go"}
_ = (, "T", args2)
}
import (
"html/template"
"os"
)
type Info struct{
Username string
MainPage string
}
func main() {
t, _ := ("demo").Parse(`{{define "T"}}Hello, {{.Username}}! Main Page: [{{.MainPage}}]{{end}}`)
args2 := Info{Username: "Hypermind", MainPage: "/go"}
_ = (, "T", args2)
}
Iterative display of two-dimensional arrays
Copy the codeThe code is as follows:
package main
import (
"html/template"
"os"
)
type Matrix struct {
Array [9][9]int
}
func main() {
tmpl, _ := ("example").Parse(`
{{ $a := .Array }}
{{ range $a }}{{ $elem := . }}|{{ range $elem }}{{ printf "%d" . }}{{ end}}|
{{end}}`)
(, matrix)
}
import (
"html/template"
"os"
)
type Matrix struct {
Array [9][9]int
}
func main() {
tmpl, _ := ("example").Parse(`
{{ $a := .Array }}
{{ range $a }}{{ $elem := . }}|{{ range $elem }}{{ printf "%d" . }}{{ end}}|
{{end}}`)
(, matrix)
}
I hope this article will be helpful to everyone's Go language programming.