beego框架 模板函数

本文介绍 beego 默认新增的模板函数,Go 内置模板引擎也自带了一些模板函数。

提示:点击连接了解Go html/template内置模板函数

 

1. beego 内置模板函数

函数名说明例子
dateformat实现了时间的格式化,返回字符串{{dateformat .Time "2006-01-02T15:04:05Z07:00"}}。
date类似php的date函数,用于格式化时间{{date .Time "Y-m-d H:i:s"}}
compare实现了比较两个对象的比较,如果相同返回 true,否者 false{{compare .A .B}}
substr实现了字符串的截取{{substr .Str 0 20}}
html2str实现了把 html 转化为字符串,剔除一些 script、css 之类的元素{{html2str .Htmlinfo}}
str2html实现了把相应的字符串当作 HTML 来输出,不转义{{str2html .Strhtml}}
htmlquote实现了基本的 html 字符转义{{htmlquote .content}}
htmlunquote实现了基本的反转移字符{{htmlunquote .content}}
renderform根据 StructTag 直接生成对应的表单{{&structData | renderform}}
assets_js为 js 文件生成一个 <script> 标签{{assets_js srcPath}}
assets_css为 css 文件生成一个 <link> 标签{{assets_css srcPath}}
config获取 AppConfig 的值, 用于读取配置文件信息, 可选的 configType 有 String, Bool, Int, Int64, Float, DIY{{config configType configKey defaultValue}}
urlfor获取控制器方法的 URL{{urlfor "UserController.Get"}}

 

2. 自定义模板函数

除了使用 beego 提供的默认模板函数,我们也可以定义新的模板函数,下面是 beego 对 html/template 封装后定义模板函数的例子:

// 定义模板函数, 自动在字符串后面加上标题
func demo(in string)(out string){
    out = in + " - 欢迎访问梯子教程"
    return
}

// 注册模板函数
beego.AddFuncMap("helloFunc",demo)

下面是调用自定义模板函数例子:

{{.title | helloFunc}}

beego 静态资源路径设置:我们在使用beego开发项目的时候,除了 html 模板之外,往往还存在 js、css 和图片等静态资源文件,beego 如何处理这些静态文件呢?beego 默认静态资源通常保存在 static 目录,访问静态资源的 url 的方式:http://域名/static/资源路径名。