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.go28 chars2 lines
Next, you need to parse the template string using the "template.Must" function, which returns a new "Template" object:
main.go76 chars5 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.go69 chars5 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.go273 chars17 lines
This will output the following string: "Name: John, Age: 30".
gistlibby LogSnag