beego模板函數(shù)

2023-11-21 10:45 更新
beego 支持用戶定義模板函數(shù),但是必須在 `beego.Run()` 調(diào)用之前,設(shè)置如下:

    func hello(in string)(out string){
        out = in + "world"
        return
    }

    beego.AddFuncMap("hi",hello)

定義之后你就可以在模板中這樣使用了:

    {{.Content | hi}}

目前 beego 內(nèi)置的模板函數(shù)如下所示:

* dateformat

    實現(xiàn)了時間的格式化,返回字符串,使用方法 {{dateformat .Time "2006-01-02T15:04:05Z07:00"}}。

* date

    實現(xiàn)了類似 PHP 的 date 函數(shù),可以很方便的根據(jù)字符串返回時間,使用方法 {{date .T "Y-m-d H:i:s"}}。

* compare

    實現(xiàn)了比較兩個對象的比較,如果相同返回 true,否者 false,使用方法 {{compare .A .B}}。

* substr

    實現(xiàn)了字符串的截取,支持中文截取的完美截取,使用方法 {{substr .Str 0 30}}。

* html2str

    實現(xiàn)了把 html 轉(zhuǎn)化為字符串,剔除一些 script、css 之類的元素,返回純文本信息,使用方法 {{html2str .Htmlinfo}}。

* str2html

    實現(xiàn)了把相應(yīng)的字符串當(dāng)作 HTML 來輸出,不轉(zhuǎn)義,使用方法 {{str2html .Strhtml}}。

* htmlquote

    實現(xiàn)了基本的 html 字符轉(zhuǎn)義,使用方法 {{htmlquote .quote}}。

* htmlunquote

    實現(xiàn)了基本的反轉(zhuǎn)移字符,使用方法 {{htmlunquote .unquote}}。

* renderform

    根據(jù) StructTag 直接生成對應(yīng)的表單,使用方法 {{&struct | renderform}}。

* assets_css

    為css文件生成一個`<link>`標(biāo)簽`. `使用方法 {{assets_css src}}

* assets_js

    為js文件生成一個`<script>`標(biāo)簽`.`使用方法 {{assets_js src}}

* config

    獲取AppConfig的值`.`使用方法 {{config configType configKey defaultValue}}`.` 可選的 configType有String,Bool,Int,Int64,Float,DIY

* map_get

    獲取 `map` 的值

    用法:

        // In controller
        Data["m"] = map[string]interface{} {
            "a": 1,
            "1": map[string]float64{
                "c": 4,
            },
        }

        // In view
        {{ map_get .m "a" }} // return 1
        {{ map_get .m 1 "c" }} // return 4

* urlfor

    獲取控制器方法的 URL

        {{urlfor "TestController.List"}}

    詳見 模板中如何使用
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號