一、自带函数
(一)print系列
1、简介
在go语言中的fmt包中存在:
- Print系列
- Sprint系列
那么它们之间的区别是什么呢?
package main
import "fmt"
func main() {
name := "lily"
fmt.Print(name) // Print有打印结果,但是Sprint没有,可以有返回值,比如 res := fmt.Sprint(name)
}
所以模板函数中print系列函数可以与go语言中的对应关系:
- print 对应 fmt.Sprint
- printf 对应 fmt.Sprintf
- println 对应 fmt.Sprintln
2、使用
- 管道符传值
{{. | printf "%s"}}
- 括号优先级
{{printf "My Name is %s" (printf "%s" .)}}
(二)and、or、not
- and 只要有一个为空,则整体为空,如果都不为空,则返回最后一个
- or 只要有一个不为空,则返回第一个不为空的,否则返回空
- not 返回输入参数的否定值
后台:
...
func BoolFunc(ctx *gin.Context) {
data := map[string]interface{}{
"arr": [3]int{1, 2, 3},
"a": "hello",
}
ctx.HTML(http.StatusOK, "and_or_not_func.html", data)
}
...
前台:
...
{{/* and的用法 [1 2 3] */}}
{{and .a .arr}}
{{/* or的用法 hello */}}
{{or .a .arr}}
{{/* not的用法 false */}}
{{not .arr}}
...
(三)index、len
- index 读取指定类型对应下标的值,支持 map、slice、array、string类型
- len 返回对应类型的长度,支持map、slice、array、string、chan类型
后台:
...
func IndexFunc(ctx *gin.Context) {
data := map[string]interface{}{
"arr": [3]int{1, 2, 3},
"map_data": map[string]string{
"name": "alice",
"addr": "beijing",
},
}
ctx.HTML(http.StatusOK, "index_len_func.html", data)
}
...
前台:
...
{{/* index的使用 */}}
{{index .arr 0}}
{{index .map_data "name"}}
<br>
{{/* len的使用 */}}
{{.arr len}}
...
(四)eq、ne、lt、le、gt、ge
- eq 等于
- ne 不等于
- lt 小于
- le 小于等于
- gt 大于
- ge 大于等于
后台:
...
func CompareFunc(ctx *gin.Context) {
age := 20
ctx.HTML(http.StatusOK, "compare_func.html", age)
}
...
前台:
...
{{/* 比较运算符的使用 */}}
{{eq . 18}}
{{eq . 20 18 17}} {{/* eq比较特殊的是可以和多个进行比较 */}}
{{ne . 18}}
{{lt . 18}}
{{le . 18}}
{{gt . 18}}
{{ge . 18}}
...
(五)Format
进行时间格式化,返回字符串。时间设置注意的是,比如这样的格式 “2006/01/02 15:04:05″,格式可以变,但是数值不要变。
后台:
...
func FormatFunc(ctx *gin.Context) {
now_time := time.Now().Format("2006-01-02 15:04:05")
ctx.HTML(http.StatusOK, "time_format_func.html", now_time)
}
...
前台:
...
{{.}}
...
(六)总结
var builtins = FuncMap{
"and": and,
"call": call,
"html": HTMLEscaper,
"index": index,
"js": JSEscaper,
"len": length,
"not": not,
"or": or,
"print": fmt.Sprint,
"printf": fmt.Sprintf,
"println": fmt.Sprintln,
"urlquery": URLQueryEscaper,
// Comparisons
"eq": eq, // ==
"ge": ge, // >=
"gt": gt, // >
"le": le, // <=
"lt": lt, // <
"ne": ne, // !=
}
二、自定义函数
步骤:
- 定义函数
- SetFuncMap
- 前端使用
1、定义函数
func add(a int, b int) int {
return a + b
}
2、SetFuncMap
...
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"Add": add, // 字符串名称前端使用
})
router.LoadHTMLGlob("template/*")
router.GET("/define_func", DefineFunc)
router.Run(":8080")
}
...
3、前端使用
...
{{Add 1 2}}
...
原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/245235.html