我想使用string.ToUpper
大写Golang模板中的字符串,如下所示:
{{ .Name | strings.ToUpper }}
但这不起作用,因为strings
不是我数据的属性.
我不能导入strings
个包裹,因为系统警告我它没有使用.
我想使用string.ToUpper
大写Golang模板中的字符串,如下所示:
{{ .Name | strings.ToUpper }}
但这不起作用,因为strings
不是我数据的属性.
我不能导入strings
个包裹,因为系统警告我它没有使用.
只需使用像这样的FuncMap(playground)将ToHigh函数注入到您的模板中即可.
import (
"bytes"
"fmt"
"strings"
"text/template"
)
type TemplateData struct {
Name string
}
func main() {
funcMap := template.FuncMap{
"ToUpper": strings.ToUpper,
}
tmpl, _ := template.New("myTemplate").Funcs(funcMap).Parse(string("{{ .Name | ToUpper }}"))
templateDate := TemplateData{"Hello"}
var result bytes.Buffer
tmpl.Execute(&result, templateDate)
fmt.Println(result.String())
}