Golang?Template實(shí)現(xiàn)自定義函數(shù)的操作指南
更新時(shí)間:2025年02月07日 09:33:43 作者:老大白菜
這篇文章主要為大家詳細(xì)介紹了Golang如何利用Template實(shí)現(xiàn)自定義函數(shù)的操作,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
1. 基礎(chǔ)用法
1.1 創(chuàng)建簡單模板函數(shù)
package main
import (
"html/template"
"os"
)
func main() {
// 創(chuàng)建自定義函數(shù)映射
funcMap := template.FuncMap{
"upper": strings.ToUpper,
"lower": strings.ToLower,
}
// 創(chuàng)建模板并添加函數(shù)
tmpl := template.New("test").Funcs(funcMap)
// 解析模板內(nèi)容
tmpl, err := tmpl.Parse(`
原始字符串: {{.}}
大寫: {{upper .}}
小寫: {{lower .}}
`)
if err != nil {
panic(err)
}
// 執(zhí)行模板
err = tmpl.Execute(os.Stdout, "Hello, World!")
}
1.2 帶參數(shù)的模板函數(shù)
package main
import (
"html/template"
"os"
)
func main() {
funcMap := template.FuncMap{
"add": func(a, b int) int {
return a + b
},
"multiply": func(a, b int) int {
return a * b
},
}
tmpl := template.New("calc").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
{{add 5 3}} = 8
{{multiply 4 6}} = 24
`)
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, nil)
}
2. 高級(jí)用法
2.1 條件判斷函數(shù)
package main
import (
"html/template"
"os"
)
func main() {
funcMap := template.FuncMap{
"isEven": func(n int) bool {
return n%2 == 0
},
"ifThenElse": func(condition bool, a, b interface{}) interface{} {
if condition {
return a
}
return b
},
}
tmpl := template.New("conditions").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
{{range $i := .}}
數(shù)字 {{$i}} 是: {{if isEven $i}}偶數(shù){{else}}奇數(shù){{end}}
另一種寫法: {{ifThenElse (isEven $i) "偶數(shù)" "奇數(shù)"}}
{{end}}
`)
if err != nil {
panic(err)
}
numbers := []int{1, 2, 3, 4, 5}
err = tmpl.Execute(os.Stdout, numbers)
}
2.2 格式化函數(shù)
package main
import (
"fmt"
"html/template"
"os"
"time"
)
func main() {
funcMap := template.FuncMap{
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
},
"formatPrice": func(price float64) string {
return fmt.Sprintf("¥%.2f", price)
},
}
tmpl := template.New("format").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
當(dāng)前時(shí)間: {{formatDate .Time}}
商品價(jià)格: {{formatPrice .Price}}
`)
if err != nil {
panic(err)
}
data := struct {
Time time.Time
Price float64
}{
Time: time.Now(),
Price: 99.99,
}
err = tmpl.Execute(os.Stdout, data)
}
2.3 切片操作函數(shù)
package main
import (
"html/template"
"os"
)
func main() {
funcMap := template.FuncMap{
"first": func(x []interface{}) interface{} {
if len(x) > 0 {
return x[0]
}
return nil
},
"last": func(x []interface{}) interface{} {
if len(x) > 0 {
return x[len(x)-1]
}
return nil
},
"slice": func(x []interface{}, start, end int) []interface{} {
if start < 0 {
start = 0
}
if end > len(x) {
end = len(x)
}
return x[start:end]
},
}
tmpl := template.New("slice").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
完整切片: {{.}}
第一個(gè)元素: {{first .}}
最后一個(gè)元素: {{last .}}
切片[1:3]: {{slice . 1 3}}
`)
if err != nil {
panic(err)
}
data := []interface{}{1, 2, 3, 4, 5}
err = tmpl.Execute(os.Stdout, data)
}
3. 實(shí)用示例
3.1 HTML 安全轉(zhuǎn)義
package main
import (
"html/template"
"os"
)
func main() {
funcMap := template.FuncMap{
"safe": func(s string) template.HTML {
return template.HTML(s)
},
"safeAttr": func(s string) template.HTMLAttr {
return template.HTMLAttr(s)
},
}
tmpl := template.New("safe").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
普通文本: {{.Text}}
HTML內(nèi)容: {{safe .HTML}}
屬性值: <div {{safeAttr .Attr}}></div>
`)
if err != nil {
panic(err)
}
data := struct {
Text string
HTML string
Attr string
}{
Text: "<b>文本</b>",
HTML: "<b>HTML</b>",
Attr: `style="color: red"`,
}
err = tmpl.Execute(os.Stdout, data)
}
3.2 數(shù)據(jù)過濾和轉(zhuǎn)換
package main
import (
"html/template"
"os"
"strings"
)
func main() {
funcMap := template.FuncMap{
"join": strings.Join,
"split": strings.Split,
"title": strings.Title,
"filter": func(arr []string, f func(string) bool) []string {
var result []string
for _, v := range arr {
if f(v) {
result = append(result, v)
}
}
return result
},
}
tmpl := template.New("filter").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
原始數(shù)組: {{.}}
Join結(jié)果: {{join . ","}}
Split結(jié)果: {{split "a,b,c" ","}}
Title結(jié)果: {{title "hello world"}}
Filter結(jié)果: {{filter . (lambda "len" "gt" 3)}}
`)
if err != nil {
panic(err)
}
data := []string{"apple", "banana", "orange", "pear"}
err = tmpl.Execute(os.Stdout, data)
}
4. 最佳實(shí)踐
4.1 模板函數(shù)組織
// template_funcs.go
package template
import "html/template"
// 創(chuàng)建全局函數(shù)映射
var GlobalFuncMap = template.FuncMap{
// 字符串操作
"upper": strings.ToUpper,
"lower": strings.ToLower,
"title": strings.Title,
// 數(shù)值操作
"add": func(a, b int) int { return a + b },
"subtract": func(a, b int) int { return a - b },
"multiply": func(a, b int) int { return a * b },
"divide": func(a, b int) float64 { return float64(a) / float64(b) },
// 日期操作
"formatDate": func(t time.Time, layout string) string { return t.Format(layout) },
"now": time.Now,
// 切片操作
"first": first,
"last": last,
"slice": slice,
// 條件操作
"isEven": isEven,
"ifThenElse": ifThenElse,
}
// 在應(yīng)用中使用
func main() {
tmpl := template.New("page").Funcs(GlobalFuncMap)
// ... 其他操作
}
4.2 錯(cuò)誤處理
package main
import (
"html/template"
"os"
)
func main() {
funcMap := template.FuncMap{
"divide": func(a, b int) (string, error) {
if b == 0 {
return "", fmt.Errorf("除數(shù)不能為零")
}
return fmt.Sprintf("%.2f", float64(a)/float64(b)), nil
},
}
tmpl := template.New("error").Funcs(funcMap)
tmpl, err := tmpl.Parse(`
{{with $result := divide 10 2}}
結(jié)果: {{$result}}
{{else}}
計(jì)算出錯(cuò)
{{end}}
`)
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, nil)
}
總結(jié)
1.基本原則
- 保持函數(shù)簡單明確
- 注意類型安全
- 適當(dāng)處理錯(cuò)誤
- 避免過度復(fù)雜的邏輯
2.常見用途
- 文本格式化
- 數(shù)據(jù)轉(zhuǎn)換
- 條件判斷
- 集合操作
- HTML 安全處理
3.性能考慮
- 緩存模板
- 避免重復(fù)解析
- 合理使用內(nèi)存
到此這篇關(guān)于Golang Template實(shí)現(xiàn)自定義函數(shù)的操作指南的文章就介紹到這了,更多相關(guān)Go Template自定義函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang實(shí)現(xiàn)讀取excel文件并轉(zhuǎn)換為JSON格式
本文介紹了如何使用Golang讀取Excel文件并將其轉(zhuǎn)換為JSON格式,通過安裝excelize依賴和創(chuàng)建readExcelToJSON方法,可以實(shí)現(xiàn)這一功能,如果需要轉(zhuǎn)換數(shù)據(jù)類型,可以修改相應(yīng)的代碼,需要的朋友可以參考下2025-03-03
golang連接MongoDB數(shù)據(jù)庫及數(shù)據(jù)庫操作指南
MongoDB是Nosql中常用的一種數(shù)據(jù)庫,下面這篇文章主要給大家介紹了關(guān)于golang連接MongoDB數(shù)據(jù)庫及數(shù)據(jù)庫操作的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
GoFrame框架gset交差并補(bǔ)集使用實(shí)例
這篇文章主要為大家介紹了GoFrame框架gset交差并補(bǔ)集使用實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
深入解析快速排序算法的原理及其Go語言版實(shí)現(xiàn)
這篇文章主要介紹了快速排序算法的原理及其Go語言版實(shí)現(xiàn),文中對(duì)于快速算法的過程和效率有較為詳細(xì)的說明,需要的朋友可以參考下2016-04-04

