• 内置变量
    • ghttp内置变量
      • Config
      • Cookie
      • Session
      • Get
      • Post
  • 变量对象

    内置变量

    ghttp内置变量

    以下内置模板变量仅在WebServer下,即通过ghttp模块使用ghttp.Response/gmvc.View对象渲染模板引擎时有效。

    Config

    访问默认的配置管理(config.toml)对象配置项。

    使用方式

    1. {{.Config.配置项}}

    访问当前请求的Cookie对象参数值。

    使用方式

    1. {{.Cookie.键名}}

    Session

    访问当前请求的Session对象参数值。

    使用方式

    1. {{.Session.键名}}

    Get

    访问当前GET请求的Get请求参数值。

    使用方式

    1. {{.Get.键名}}

    Post

    访问当前POST请求的Post请求参数值。

    使用方式

    1. {{.Post.键名}}

    使用示例:

    1. package main
    2. import (
    3. "github.com/gogf/gf/g"
    4. "github.com/gogf/gf/g/net/ghttp"
    5. )
    6. func main() {
    7. s := g.Server()
    8. s.BindHandler("/", func(r *ghttp.Request){
    9. r.Cookie.Set("theme", "default")
    10. r.Session.Set("name", "john")
    11. content :=`Config:{{.Config.redis.cache}}, Cookie:{{.Cookie.theme}}, Session:{{.Session.name}}, Get:{{.Get.name}}`
    12. r.Response.WriteTplContent(content, nil)
    13. })
    14. s.SetPort(8199)
    15. s.Run()
    16. }

    其中,config.toml内容为:

    1. # Redis数据库配置
    2. [redis]
    3. disk = "127.0.0.1:6379,0"
    4. cache = "127.0.0.1:6379,1"

    执行后,访问http://127.0.0.1:8199/?name=john,输出结果为:

    1. Config:127.0.0.1:6379,1, Cookie:default, Session:john, Get:john

    变量对象

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

    示例:

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

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

    执行后,输出结果为:

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