From 45af2e59bbbf9e08014bda2d894b402f574c9516 Mon Sep 17 00:00:00 2001 From: xengineering Date: Fri, 8 Nov 2024 17:00:09 +0100 Subject: Add example for usage in Go templates --- optional/template_test.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 optional/template_test.go diff --git a/optional/template_test.go b/optional/template_test.go new file mode 100644 index 0000000..ab4ce76 --- /dev/null +++ b/optional/template_test.go @@ -0,0 +1,34 @@ +package optional_test + +import ( + "html/template" + "log" + "os" + + "xengineering.eu/optional-go/optional" +) + +func ExampleTemplate() { + data := struct { + Flag optional.Optional[bool] + }{ + Flag: optional.Optional[bool]{ + Value: false, + Exists: false, + }, + } + + tmpl := `Flag is: {{if .Flag.Exists}}{{.Flag.Value}}{{else}}[none]{{end}}` + + t, err := template.New("optional").Parse(tmpl) + if err != nil { + log.Fatal(err) + } + + err = t.Execute(os.Stdout, data) + if err != nil { + log.Fatal(err) + } + + // Output: Flag is: [none] +} -- cgit v1.2.3-70-g09d2