我希望使用string.ToUpper在golang模板中大写一个字符串,如:
- {{ .Name | strings.ToUpper }}
但这不起作用,因为字符串不是我数据的属性.
我无法导入字符串包,因为它警告我它没有被使用.
只需使用像这样的
FuncMap(
playground)将ToUpper功能注入模板.
- 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())
- }