正如摘要所述,本文将深入探讨 Go 语言中模板函数的使用,特别是自定义格式化函数与作用域的问题。我们将分析 template.FormatterMap 的定义和 template.HTMLEscape 函数的签名,解释为何需要包装函数 UrlHtmlFormatter。
在 Go 语言的 text/template 和 html/template 包中,FormatterMap 用于将字符串键映射到格式化函数。这些格式化函数允许我们在模板中对数据进行自定义处理。
FormatterMap 的类型定义如下:
type FormatterMap map[string]func(io.Writer, interface{}, string)
这意味着 FormatterMap 中的每个值都必须是一个函数,该函数接受一个 io.Writer、一个 interface{} 和一个 string 作为参数。
另一方面,template.HTMLEscape 函数的签名如下:
func HTMLEscape(w io.Writer, b []byte)
它接受一个 io.Writer 和一个字节切片 []byte 作为参数。
由于 template.HTMLEscape 函数的签名与 FormatterMap 中所需函数的签名不匹配,因此我们需要一个适配器函数,也就是 UrlHtmlFormatter。
func UrlHtmlFormatter(w io.Writer, v interface{}, fmt string) { template.HTMLEscape(w, []byte(http.URLEscape(v.(string)))) }
UrlHtmlFormatter 函数接收 FormatterMap 所需的参数,并将 interface{} 类型的 v 转换为字符串,然后进行 URL 转义和 HTML 转义,最后调用 template.HTMLEscape 函数。这样,我们就可以在模板中使用 "url+html" 键来调用这个自定义的格式化函数。
以下是完整的示例代码,展示了如何使用自定义格式化函数:
package main import ( "flag" "fmt" "html/template" "io" "log" "net/http" "net/url" ) var addr = flag.String("addr", ":1718", "http service address") var fmap = template.FuncMap{ "html": template.HTMLEscapeString, "url+html": UrlHtmlFormatter, } var templ = template.Must(template.New("qr").Funcs(fmap).Parse(templateStr)) func main() { flag.Parse() http.HandleFunc("/", QR) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe:", err) } } func QR(w http.ResponseWriter, req *http.Request) { err := templ.Execute(w, req.FormValue("s")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func UrlHtmlFormatter(v interface{}) template.HTML { escapedURL := url.QueryEscape(fmt.Sprint(v)) escapedHTML := template.HTMLEscapeString(escapedURL) return template.HTML(escapedHTML) } const templateStr = ` <html> <head> <title>QR Link Generator</title> </head> <body> {{if .}} @@##@@ <br> {{.|html}} <br> <br> {{end}} <form action="/" name=f method="GET"><input maxLength=1024 size=70 name=s value="" title="Text to QR Encode"><input type=submit value="Show QR" name=qr> </form> </body> </html> `
本文详细解释了 Go 语言中自定义模板格式化函数的原因和方法。通过理解 FormatterMap 的定义和函数签名,我们可以创建自定义的格式化函数,并在模板中灵活使用。同时,我们也需要注意类型安全和安全漏洞,以确保程序的稳定性和安全性。
通过本文的学习,读者可以掌握 Go 语言中模板函数的使用,并能够根据实际需求创建自定义的格式化函数,从而更好地控制模板的输出。
以上就是Go 语言中模板函数与作用域详解:自定义格式化及参数传递的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号