zoukankan      html  css  js  c++  java
  • [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



  • 相关阅读:
    Delphi StrUtils-字符串函数RightStr、MidStr、LeftStr
    Delphi 错误:Could not convert variant to type(Null) into type (String)
    Delphi Variants-VarIsEmpty、VarIsNull 判断Variant变量是否为空、是否包含Null值
    Python使用openpyxl读写excel文件
    CentOS7设置为局域网固定ip
    Linux下ps aux命令中STAT的参数含义(转)
    Python生成8位随机字符串的方法分析
    php源码加密方法详解
    普通程序员 与 大牛 的区别 ???
    开始记录前端学习过程中的点点滴滴
  • 原文地址:https://www.cnblogs.com/dfsxh/p/10222598.html
Copyright © 2011-2022 走看看