Introduction

Developers can define custom template functions and globally bind them to specified view objects.

Template Funcs - Custom - 图1tip

Custom objects can also be assigned to templates, allowing method calls on those objects.

Example

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. )
  7. // Test built-in function with parameters
  8. func funcHello(name string) string {
  9. return fmt.Sprintf(`Hello %s`, name)
  10. }
  11. func main() {
  12. // Bind global template function
  13. g.View().BindFunc("hello", funcHello)
  14. // Pass parameters in a regular way
  15. parsed1, err := g.View().ParseContent(context.TODO(), `{{hello "GoFrame"}}`, nil)
  16. if err != nil {
  17. panic(err)
  18. }
  19. fmt.Println(string(parsed1))
  20. // Pass parameters through a pipeline
  21. parsed2, err := g.View().ParseContent(context.TODO(), `{{"GoFrame" | hello}}`, nil)
  22. if err != nil {
  23. panic(err)
  24. }
  25. fmt.Println(string(parsed2))
  26. }

After execution, the output is:

  1. Hello GoFrame
  2. Hello GoFrame