Text Templates
// Importing necessary packages.
import (
"os"
"text/template"
)
// The main function, where the execution of the program begins.
func main() {
// Creating a new template named "t1" and parsing a simple template string.
t1 := template.New("t1")
t1, err := t1.Parse("Value is {{.}}\n")
if err != nil {
panic(err)
}
// Using template.Must to simplify error handling and parsing another template string.
t1 = template.Must(t1.Parse("Value: {{.}}\n"))
// Executing the template with different values and printing the result to os.Stdout.
t1.Execute(os.Stdout, "some text")
t1.Execute(os.Stdout, 5)
t1.Execute(os.Stdout, []string{
"Go",
"Rust",
"C++",
"C#",
})
// Creating a function to simplify template creation.
Create := func(name, t string) *template.Template {
return template.Must(template.New(name).Parse(t))
}
// Creating a new template "t2" using the Create function and executing it with a struct and a map.
t2 := Create("t2", "Name: {{.Name}}\n")
t2.Execute(os.Stdout, struct {
Name string
}{"Jane Doe"})
t2.Execute(os.Stdout, map[string]string{
"Name": "Mickey Mouse",
})
// Creating a new template "t3" using the Create function with a conditional statement and executing it.
t3 := Create("t3", "{{if . -}} yes {{else -}} no {{end}}\n")
t3.Execute(os.Stdout, "not empty")
t3.Execute(os.Stdout, "")
// Creating a new template "t4" using the Create function with a range statement and executing it.
t4 := Create("t4", "Range: {{range .}}{{.}} {{end}}\n")
t4.Execute(os.Stdout,
[]string{
"Go",
"Rust",
"C++",
"C#",
})
}Output
Last updated