Text Templates
This Go code demonstrates the use of the text/template
package to define and execute templates. Let's go through the code with inline comments and explanations:
Output
Explanation:
Creating and Parsing Templates:
t1
is created withtemplate.New("t1")
and parsed witht1.Parse("Value is {{.}}\n")
.template.Must
is used to simplify error handling and parse another template string.
Executing Templates:
The
Execute
function is used to execute templates with different values, printing the results toos.Stdout
.
Template Creation Function:
The
Create
function is defined to simplify template creation usingtemplate.Must
.
Using Struct and Map:
t2
is created using theCreate
function, and it is executed with both a struct and a map as input.
Conditional Statement in Template:
t3
is created using theCreate
function with a conditional statement ({{if . -}} yes {{else -}} no {{end}}
).
Range Statement in Template:
t4
is created using theCreate
function with a range statement ({{range .}}{{.}} {{end}}
), and it is executed with a slice of strings.
These examples showcase the flexibility of the text/template
package for defining and executing templates with various data structures and control structures.
Last updated
Was this helpful?