我想使用 string.ToUpper
将 golang 模板中的字符串大写,例如:
{{ .Name | strings.ToUpper }}
但这不起作用,因为 strings
不是我数据的属性。
我无法导入 strings
包,因为警告我它没有被使用。
最佳答案
只需使用 FuncMap像这样 (playground) 将 ToUpper 函数注入(inject)到您的模板中。
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())
}
关于string - Golang 模板 : Use pipe to uppercase string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031108/