Built-in Variables

Please refer to the Response - Template Parsing section for WebServer built-in variables.

Variable Objects

We can use custom objects in templates and access the properties of objects and invoke their methods within the template.

Example:

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. type T struct {
  7. Name string
  8. }
  9. func (t *T) Hello(name string) string {
  10. return "Hello " + name
  11. }
  12. func (t *T) Test() string {
  13. return "This is test"
  14. }
  15. func main() {
  16. t := &T{"John"}
  17. v := g.View()
  18. content := `{{.t.Hello "there"}}, my name's {{.t.Name}}. {{.t.Test}}.`
  19. if r, err := v.ParseContent(context.TODO(), content, g.Map{"t": t}); err != nil {
  20. g.Dump(err)
  21. } else {
  22. g.Dump(r)
  23. }
  24. }

Here, the variables assigned to the template can be either object pointers or object variables. However, note the defined object methods: if it is an object pointer, you can only call methods where the receiver is an object pointer; if it is an object variable, you can only call methods where the receiver is an object.

After execution, the output is:

  1. Hello there, my name's John. This is test.