Go Template Syntax
5/14/25About 2 mincomponenttemplatesyntax
Overview
Go's text/template
package provides a powerful and flexible way to generate text output. The following are the basic syntax rules for using text/template
:
- Template Definition: Templates are usually defined in
.tmpl
or.tpl
files. - Actions: Actions are enclosed by
{{
and}}
, used to insert data or execute logic in the template. - Variables: Variables are accessed using a dot
.
, for example{{.Name}}
. - Comments: Start with
{{/*
and end with*/}}
.
Actions
Actions are core in the template language, enclosed by {{ }}
, for example:
{{.}} // Current object
{{.Field}} // Field of the current object
{{if .Condition}} // Conditional statement
// Execute some operations
{{end}}
{{range .Items}} // Loop
{{.}}
{{end}}
Variable Declaration and Assignment
You can declare and assign variables in the template:
{{ $name := "World" }}
Hello, {{ $name }}!
Conditional Statements
The template language supports conditional statements:
{{if .Condition}}
True
{{else}}
False
{{end}}
Loops
range
can be used to iterate over arrays, slices, maps, etc.:
{{range .Items}}
Item: {{.}}
{{end}}
Getting Map Key and Value
{{range $key, $val := .Map}}
print("{{$key}}", "{{$val}}")
{{end}}
Referencing Variables from the Outer Scope
{{range .Services}}
print("{{.ServiceName}}")
{{ $serviceName := .ServiceName }}
{{range .Methods}}
print("{{$serviceName}}") // Here, reference the ServiceName from the outer Service struct in the inner scope
{{end}}
{{end}}
Functions
Predefined or custom functions can be called in templates:
// Define a struct as the data source for the template
type User struct {
Name string
Age int
Email string
}
// Custom function example
func getCurrentYear() int {
return time.Now().Year()
}
func defineTemplate() {
// Define the template
tmpl := template.New("example")
// Add predefined functions
tmpl = tmpl.Funcs(template.FuncMap{
"uppercase": strings.ToUpper, // Use a function from the standard library
"now": time.Now,
})
// Add custom functions
tmpl = tmpl.Funcs(template.FuncMap{
"year": getCurrentYear,
})
// Define template content
const tmplText = `
Hello {{.Name}},
Your email is: {{.Email}}
Your age in {{now | year}} will be {{add .Age 1}}.
And here's your name in uppercase: {{uppercase .Name}}
`
// Parse template content
)
Removing Whitespace and Newlines
In text/template
, the purpose of {{-
and -}}
is to remove whitespace characters around template tags. Specifically, they can remove whitespace characters (such as spaces, newlines) to the left or right of the tag.
{{- range .Items}}
{{.Name}}
{{- end}}