golang template if
package main
import (
"os"
"text/template"
)
func main() {
const tmpl = `{{if .}}Not empty{{else}}Empty{{end}}`
t := template.Must(template.New("tmpl").Parse(tmpl))
data := []int{1, 2, 3}
if err := t.Execute(os.Stdout, data); err != nil {
panic(err)
}
}
Explanation:
1. package main
: Specifies that this Go file belongs to the main package, which is the entry point for the executable program.
import
: Imports necessary packages.os
is used for operating system functionality, andtext/template
provides support for text templates.func main() { ... }
: Defines the main function, which is the entry point of the program.const tmpl =
{{if .}}Not empty{{else}}Empty{{end}}`: Defines a constant
tmplcontaining a text template. The template uses the
{{if}}conditional action to check if the provided data (denoted by
.`) is not empty. If it's not empty, it will print "Not empty"; otherwise, it will print "Empty".t := template.Must(template.New("tmpl").Parse(tmpl))
: Creates a new template named "tmpl" usingtemplate.New("tmpl")
. TheParse
function parses the template defined earlier and returns a pointer to aTemplate
struct.template.Must
is used to handle any parsing errors by panicking if an error occurs.data := []int{1, 2, 3}
: Initializes a slice nameddata
containing integers 1, 2, and 3.if err := t.Execute(os.Stdout, data); err != nil { panic(err) }
: Executes the templatet
by applying it to thedata
slice. If any error occurs during execution, it will be caught and the program will panic, halting its execution.
This program demonstrates the use of the if
conditional action within a Go template to check if the provided data is empty or not, and then prints the corresponding message based on that condition.