I18N变量

执行后,输出结果为:(保证当前运行目录带有i18n转译配置文件)

  1. john says "你好世界!"
  2. john says "こんにちは世界!"

HTTP对象视图

gf框架的WebServer的返回对象中提供了基础的模板解析方法,如下:

  1. func (r *Response) WriteTpl(tpl string, params map[string]interface{}, funcMap ...map[string]interface{}) error
  2. func (r *Response) WriteTplContent(content string, params map[string]interface{}, funcMap ...map[string]interface{}) error

其中WriteTpl用于输出模板文件,WriteTplContent用于直接解析输出模板内容。

执行后,输出结果为:

  1. Cookie:default, Session:john

控制器视图管理

gf为路由控制器注册方式提供了良好的模板引擎支持,由gmvc.View视图对象进行管理,提供了良好的数据隔离性。控制器视图是并发安全设计的,允许在多线程中异步操作。

  1. func (view *View) Assign(key string, value interface{})
  2. func (view *View) Assigns(data gview.Params)
  3. func (view *View) Parse(file string) ([]byte, error)
  4. func (view *View) ParseContent(content string) ([]byte, error)
  5. func (view *View) Display(files ...string) error
  6. func (view *View) DisplayContent(content string) error
  7. func (view *View) LockFunc(f func(vars map[string]interface{}))
  8. func (view *View) RLockFunc(f func(vars map[string]interface{}))

其中的模板内容如下:

  1. <html>
  2. <head>
  3. <title>gf template engine</title>
  4. <body>
  5. <p>Name: {{.name}}</p>
  6. <p>Age: {{.age}}</p>
  7. <p>Score:{{.score}}</p>
  8. </body>
  9. </html>

执行后,访问 http://127.0.0.1:8199/template/info 可以看到模板被解析并展示到页面上。如果页面报错找不到模板文件,没有关系,因为这里并没有对模板目录做设置,默认是当前可行文件的执行目录(Linux&Mac下是/tmp目录,Windows下是C:\Documents and Settings\用户名\Local Settings\Temp)。

其中,给定的模板文件file参数是需要带完整的文件名后缀,例如:index.tplindex.html等等,模板引擎对模板文件后缀名没有要求,用户可完全自定义。此外,模板文件参数也支持文件的绝对路径(完整的文件路径)。

  1. package main
  2. import (
  3. "github.com/gogf/gf/net/ghttp"
  4. "github.com/gogf/gf/frame/gmvc"
  5. )
  6. type ControllerTemplate struct {
  7. gmvc.Controller
  8. }
  9. c.View.Assign("name", "john")
  10. c.View.Assigns(map[string]interface{}{
  11. "age" : 18,
  12. })
  13. c.View.DisplayContent(`
  14. <html>
  15. <head>
  16. <title>gf template engine</title>
  17. </head>
  18. <body>
  19. <p>Name: {{.name}}</p>
  20. <p>Age: {{.age}}</p>
  21. <p>Score:{{.score}}</p>
  22. </body>
  23. </html>
  24. `)
  25. }
  26. func main() {
  27. s := ghttp.GetServer()
  28. s.BindController("/template", new(ControllerTemplate{}))
  29. s.SetPort(8199)
  30. s.Run()
  31. }

执行后,访问 可以看到解析后的内容如下: