]> Cypherpunks repositories - gostls13.git/commitdiff
text/template: add an if func example
authorlinmaolin <linlin152@foxmail.com>
Thu, 6 Mar 2025 00:41:02 +0000 (00:41 +0000)
committerGopher Robot <gobot@golang.org>
Fri, 7 Mar 2025 19:32:13 +0000 (11:32 -0800)
Updates #13880

Change-Id: I0fd3b1a32e485bc8f15238c86a8bbdc161f20fa5
GitHub-Last-Rev: d1e92b31243c86435add422ee46aaff768453cad
GitHub-Pull-Request: golang/go#71922
Reviewed-on: https://go-review.googlesource.com/c/go/+/651916
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>

src/text/template/examplefunc_test.go

index a114a466011aa89d0ddc04383df2558b5da6b3aa..a1879e7c3f988eb399034c765b54d7eb941bfd9e 100644 (file)
@@ -96,3 +96,28 @@ func ExampleTemplate_funcs() {
        // def
        // def
 }
+
+// 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.
+}