Member-only story
What is template Module
The template package (https://pkg.go.dev/text/template) in Go provides data-driven templates for generating textual output. This package, along with the related html/template package, are powerful tools for generating any kind of text in a flexible, dynamic manner, from HTML or JSON files to configuration files or source code.
The template package offers two key types: Template and FuncMap.
Template
: TheTemplate
type represents a parsed template. It can be created with thetemplate.New
function and then parsed from a string or file.FuncMap
: TheFuncMap
type is a map of functions that can be used in a template. This allows you to pass custom functions to your template and use them when generating output.
Here is a simple example of how you can use the template package:
package main
import (
"os"
"text/template"
)
type Person struct {
Name string
Age int
}
func main() {
t := template.New("person template")
t, _ = t.Parse("Name: {{.Name}}, Age: {{.Age}}\n")
p := Person{Name: "John Smith", Age: 30}
t.Execute(os.Stdout, p)
}
In this example, we define a new template with a placeholder for name and age. We then…