name: Template Functions

sort: 2

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. {{dateformat .Time “2006-01-02T15:04:05Z07:00”}}

  • date

    This is similar to date function in PHP. It can easily return time by string {{date .T “Y-m-d H:i:s”}}

  • compare

    Compare two objects. If they are the same return true otherwise return false. {{compare .A .B}}

  • substr

    Return sub string. supports UTF-8 string. {{substr .Str 0 30}}

  • html2str

    Parse html to string by removing tags like script and css and return text. {{html2str .Htmlinfo}}

  • str2html Parse string to HTML, no escaping. {{str2html .Strhtml}}

  • htmlquote

    Escaping html. {{htmlquote .quote}}

  • htmlunquote

    Unescaping to html. {{htmlunquote .unquote}}

  • renderform

    Generate form from StructTag. {{&struct | renderform}}

  • assets_js

    Create a <script> tag from js src. {{assets_js src}}

  • assets_css

    Create a <link> tag from css src. {{assets_css src}}

  • config

    Get the value of AppConfig. {{config configType configKey defaultValue}}. configType must be String, Bool, Int, Int64, Float, or DIY

  • 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"}}

    more details