goweb3-自定义函数

预定义函数

执行模板时,函数从两个函数字典中查找:首先是模板函数字典,然后是全局函数字典。一般不在模板内定义函数,而是使用Funcs方法添加函数到模板里。

自定义组件例子

1定义模板 循环获取名字

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello</title>
</head>
<body>
    {{ range $name := .names }}
    <p>{{personName1 $name}}</p>
    {{end}}
</body>
</html>

2

//自定义函数
func customFunc(w http.ResponseWriter, r *http.Request) {
	htmlByte, err := ioutil.ReadFile("./hello.tmpl")
	if err != nil {
		fmt.Println("read html failed,err:", err)
	}
	//自定义一个模板函数
	//解析模板之前,注册一个新函数(该函数要么只有一个返回值,要么有两个,第二个必须是error类型)
	personName := func(arg string) (string, error) {
		return "我的名字叫:"+arg, nil
	}
        //解析模板
	//采用链式操作在Parse之前调用Funcs添加自定义的personName函数
	tmpl, err := template.New("hello.tmpl").Funcs(template.FuncMap{"personName1": personName}).Parse(string(htmlByte))
	//或者创建一个名字是hello.tmpl的模板对象,名字一定要与模板名字能对应上
	//t:=template.New("hello.tmpl")
	//告诉模板引擎,现在多了一个自定义函数personName
	//t.Funcs(template.FuncMap{"personName2": personName})
	//tmpl1, err1 := t.ParseFiles("./hello.tmpl")
	if err != nil {
		fmt.Println("create template failed,err:", err)
	}
	slice := []string{"zhao", "qian", "sun", "li"}
       
	//渲染模板,并将结果写入w
	tmpl.Execute(w, map[string]interface{}{
		"names": slice,
	})
}
func main() {
	http.HandleFunc("/hello", customFunc)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Println("HTTP server failed,err:", err)
		return
	}
}

所有博客均为自己学习的笔记。如有错误敬请理解。
原文地址:https://www.cnblogs.com/tangtang-benben/p/15058789.html