1. 模板函数

  1. beego 支持用户定义模板函数,但是必须在 `beego.Run()` 调用之前,设置如下:
  2. func hello(in string)(out string){
  3. out = in + "world"
  4. return
  5. }
  6. beego.AddFuncMap("hi",hello)
  7. 定义之后你就可以在模板中这样使用了:
  8. {{.Content | hi}}
  9. 目前 beego 内置的模板函数如下所示:
  10. * dateformat
  11. 实现了时间的格式化,返回字符串,使用方法 {{dateformat .Time "2006-01-02T15:04:05Z07:00"}}。
  12. * date
  13. 实现了类似 PHP date 函数,可以很方便的根据字符串返回时间,使用方法 {{date .T "Y-m-d H:i:s"}}。
  14. * compare
  15. 实现了比较两个对象的比较,如果相同返回 true,否者 false,使用方法 {{compare .A .B}}。
  16. * substr
  17. 实现了字符串的截取,支持中文截取的完美截取,使用方法 {{substr .Str 0 30}}。
  18. * html2str
  19. 实现了把 html 转化为字符串,剔除一些 scriptcss 之类的元素,返回纯文本信息,使用方法 {{html2str .Htmlinfo}}。
  20. * str2html
  21. 实现了把相应的字符串当作 HTML 来输出,不转义,使用方法 {{str2html .Strhtml}}。
  22. * htmlquote
  23. 实现了基本的 html 字符转义,使用方法 {{htmlquote .quote}}。
  24. * htmlunquote
  25. 实现了基本的反转移字符,使用方法 {{htmlunquote .unquote}}。
  26. * renderform
  27. 根据 StructTag 直接生成对应的表单,使用方法 {{&struct | renderform}}。
  28. * assets_css
  29. css文件生成一个`<link>`标签`. `使用方法 {{assets_css src}}
  30. * assets_js
  31. js文件生成一个`<script>`标签`.`使用方法 {{assets_js src}}
  32. * config
  33. 获取AppConfig的值`.`使用方法 {{config configType configKey defaultValue}}`.` 可选的 configTypeString,Bool,Int,Int64,Float,DIY
  34. * map_get
  35. 获取 `map` 的值
  36. 用法:
  37. // In controller
  38. Data["m"] = map[string]interface{} {
  39. "a": 1,
  40. "1": map[string]float64{
  41. "c": 4,
  42. },
  43. }
  44. // In view
  45. {{ map_get .m "a" }} // return 1
  46. {{ map_get .m 1 "c" }} // return 4
  47. * urlfor
  48. 获取控制器方法的 URL
  49. {{urlfor "TestController.List"}}
  50. 详见 模板中如何使用