[Beego] 內置的模板函數(不同格式的字符串和html的互轉)


在使用beego框架的時候,常常需要把不同形式的字符串轉化為html,有時候為了安全考慮會將html轉義,而有時候希望能顯示html標簽。在存儲到db中后,再取出來的顯示是原本的,即html標簽不會生效,這就需要一些內置模板函數了。

使用方法

內置函數有兩種輸出方法,在view中,可以通過{{str2html .str}}或者{{.str | str2html}} 兩種方法來輸出。

相關函數

markdown

實現了把markdown文本轉化為html信息,使用方法{{markdown .Content}}

dateformat

實現了時間的格式化,返回字符串,使用方法{{dateformat .Time “2006-01-02T15:04:05Z07:00”}}

date

實現了類似PHP的date函數,可以很方便的根據字符串返回時間,使用方法{{date .T “Y-m-d H:i:s”}}

compare

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

substr

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

html2str

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

str2html

實現了把相應的字符串當作HTML來輸出,不轉義,使用方法{{str2html .Strhtml}}

htmlquote

實現了基本的html字符轉義,使用方法{{htmlquote .quote}}

htmlunquote

實現了基本的反轉義字符,使用方法{{htmlunquote .unquote}}

assets_js

為 js 文件生成一個 <script> 標簽. 使用方法 {{assets_js src}}

assets_css

為 css 文件生成一個 <link> 標簽. 使用方法 {{assets_css src}}

自定義函數

官方的文檔里也給了自定義模板函數。

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

beego.AddFuncMap("hi",hello)

用法和以上一致,需要注意的是,beego.AddFuncMap需要在main.go里添加到beego.run之前。

現在最新版的beego已經去掉了markdown的支持,最新的模板函數如下(摘自官方源碼):

beegoTplFuncMap["dateformat"] = DateFormat
beegoTplFuncMap["date"] = Date
beegoTplFuncMap["compare"] = Compare
beegoTplFuncMap["compare_not"] = CompareNot
beegoTplFuncMap["not_nil"] = NotNil
beegoTplFuncMap["not_null"] = NotNil
beegoTplFuncMap["substr"] = Substr
beegoTplFuncMap["html2str"] = HTML2str
beegoTplFuncMap["str2html"] = Str2html
beegoTplFuncMap["htmlquote"] = Htmlquote
beegoTplFuncMap["htmlunquote"] = Htmlunquote
beegoTplFuncMap["renderform"] = RenderForm
beegoTplFuncMap["assets_js"] = AssetsJs
beegoTplFuncMap["assets_css"] = AssetsCSS
beegoTplFuncMap["config"] = GetConfig
beegoTplFuncMap["map_get"] = MapGet

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM