Go by Example: Text Templates

Go provides a package called “text/template” for processing text templates. Text templates are a way to embed dynamic data into a string, using placeholders that can be replaced with actual values at runtime.

Here’s a basic example that demonstrates how to use text templates in Go:

package main

import (
	"os"
	"text/template"
)

func main() {
	name := "John Doe"
	age := 30

	t := template.Must(template.New("template").Parse("Name: {{.Name}}, Age: {{.Age}}"))
	err := t.Execute(os.Stdout, map[string]interface{}{"Name": name, "Age": age})
	if err != nil {
		panic(err)
	}
}

In this example, two variables, name and age, are defined. The template.Must function is used to create a new template from a string, which is passed as an argument to template.New and template.Parse. The template string uses placeholders in the form of double curly braces ({{ and }}) to embed the values of name and age.

The t.Execute method is then called to execute the template and write the result to os.Stdout (the standard output). The second argument to t.Execute is a map that provides values for the template placeholders. In this example, the map has two keys, “Name” and “Age”, which correspond to the placeholders in the template string.

If the template execution is successful, the output will be:

Name: John Doe, Age: 30

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *