template_ifelse.go 889 B

123456789101112131415161718192021222324252627
  1. // template_ifelse.go
  2. package main
  3. import (
  4. "os"
  5. "text/template"
  6. )
  7. func main() {
  8. tEmpty := template.New("template test")
  9. tEmpty = template.Must(tEmpty.Parse("Empty pipeline if demo: {{if ``}} Will not print. {{end}}\n")) //empty pipeline following if
  10. tEmpty.Execute(os.Stdout, nil)
  11. tWithValue := template.New("template test")
  12. tWithValue = template.Must(tWithValue.Parse("Non empty pipeline if demo: {{if `anything`}} Will print. {{end}}\n")) //non empty pipeline following if condition
  13. tWithValue.Execute(os.Stdout, nil)
  14. tIfElse := template.New("template test")
  15. tIfElse = template.Must(tIfElse.Parse("if-else demo: {{if `anything`}} Print IF part. {{else}} Print ELSE part.{{end}}\n")) //non empty pipeline following if condition
  16. tIfElse.Execute(os.Stdout, nil)
  17. }
  18. /* Output:
  19. Empty pipeline if demo:
  20. Non empty pipeline if demo: Will print.
  21. if-else demo: Print IF part.
  22. */