Template Functions

Beego supports custom template functions but it must be set as below before web.Run():

  1. func hello(in string)(out string){
  2. out = in + "world"
  3. return
  4. }
  5. web.AddFuncMap("hi",hello)

Then you can use these functions in template:

  1. {{.Content | hi}}

Here are Beego’s built-in template functions:

  • dateformat: Format time, return string.
    1. {{dateformat .Time "2006-01-02T15:04:05Z07:00"}}
  • date: This is similar to date function in PHP. It can easily return time by string
    1. {{date .T "Y-m-d H:i:s"}}
  • compare: Compare two objects. If they are the same return true otherwise return false.
    1. {{compare .A .B}}
  • substr: Return sub string. supports UTF-8 string.
    1. {{substr .Str 0 30}}
  • html2str: Parse html to string by removing tags like script and css and return text.
    1. {{html2str .Htmlinfo}}
  • str2html: Parse string to HTML, no escaping.
    1. {{str2html .Strhtml}}
  • htmlquote: Escaping html.
    1. {{htmlquote .quote}}
  • htmlunquote: Unescaping to html.
    1. {{htmlunquote .unquote}}
  • renderform: Generate form from StructTag.
    1. {{&struct | renderform}}
  • assets_js: Create a <script> tag from js src.
    1. {{assets_js src}}
  • assets_css: Create a <link> tag from css src.
    1. {{assets_css src}}
  • config: Get the value of AppConfig and the type must be String, Bool, Int, Int64, Float, or DIY
    1. {{config configType configKey defaultValue}}
  • map_get: Get value of map by key

    1. // In controller
    2. Data["m"] = map[string]interface{} {
    3. "a": 1,
    4. "1": map[string]float64{
    5. "c": 4,
    6. },
    7. }
    8. // In view
    9. {{ map_get m "a" }} // return 1
    10. {{ map_get m 1 "c" }} // return 4
  • urlfor: Get the URL of a controller method
    1. {{urlfor "TestController.List"}}