create a template string in go

To create a template string in Go, you can use the built-in package "text/template". This package provides a simple way to format and output data from a template.

First, you need to create a template string, which is a string that contains placeholders that will be replaced with actual values at runtime. The placeholders are identified by double curly braces, like this: "{{.}}". Here's an example of a template string that contains a single placeholder:

main.go
const tpl = "Hello, {{.}}!"
28 chars
2 lines

Next, you need to parse the template string using the "template.Must" function, which returns a new "Template" object:

main.go
t, err := template.New("hello").Parse(tpl)
if err != nil {
    panic(err)
}
76 chars
5 lines

Now that you have a template object, you can execute it with a data object to replace the placeholders with actual values. The data object should be a struct or map that contains the values to be inserted into the placeholders. Here's an example that executes the template with a single string value:

main.go
err = t.Execute(os.Stdout, "world")
if err != nil {
    panic(err)
}
69 chars
5 lines

This will output the following string: "Hello, world!"

You can also use multiple placeholders in a template string and pass in a struct or map with multiple values. Here's an example:

main.go
const tpl2 = "Name: {{.Name}}, Age: {{.Age}}"
t2, err := template.New("info").Parse(tpl2)
if err != nil {
    panic(err)
}
data := struct {
    Name string
    Age  int
}{
    Name: "John",
    Age:  30,
}
err = t2.Execute(os.Stdout, data)
if err != nil {
    panic(err)
}
273 chars
17 lines

This will output the following string: "Name: John, Age: 30".

gistlibby LogSnag