Skip to content

Commit

Permalink
text/template: add an if func example
Browse files Browse the repository at this point in the history
Updates #13880
  • Loading branch information
linsite committed Mar 5, 2025
1 parent b199d97 commit 97ea47e
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/text/template/examplefunc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,28 @@ Output 2: {{printf "%q" . | title}}
// Output 1: "The Go Programming Language"
// Output 2: "The Go Programming Language"
}

// This example demonstrates how to use "if".
func ExampleTemplate_if() {
type book struct {
Stars float32
Name string
}

tpl, err := template.New("book").Parse(`{{ if (gt .Stars 4.0) }} "{{.Name }}" is a great book.{{ else }} "{{.Name}}" is not a great book. {{ end }}`)
if err != nil {
log.Fatalf("failed to parse template: %s", err)
}

b := &book{
Stars: 4.9,
Name: "Good Night, Gopher",
}
err = tpl.Execute(os.Stdout, b)
if err != nil {
log.Fatalf("failed to execute template: %s", err)
}

// Output:
// "Good Night, Gopher" is a great book.
}

0 comments on commit 97ea47e

Please sign in to comment.