内置变量

WebServer内置变量请参考 数据返回-模板解析 章节。

变量对象

我们可以在模板中使用自定义的对象,并可在模板中访问对象的属性及调用其方法。

示例:

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/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. }

其中,赋值给模板的变量既可以是对象指针也可以是对象变量。但是注意定义的对象方法,如果为对象指针那么只能调用方法接收器为对象指针的方法;如果为对象变量,那么只能调用方法接收器为对象的方法。

执行后,输出结果为:

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

Content Menu