Golang模板:使用管道大写字符串

前端之家收集整理的这篇文章主要介绍了Golang模板:使用管道大写字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望使用string.ToUpper在golang模板中大写一个字符串,如:
  1. {{ .Name | strings.ToUpper }}

但这不起作用,因为字符串不是我数据的属性.

我无法导入字符串包,因为它警告我它没有被使用.

这里的脚本:
http://play.golang.org/p/7D69Q57WcN

只需使用像这样的 FuncMap( playground)将ToUpper功能注入模板.
  1. import (
  2. "bytes"
  3. "fmt"
  4. "strings"
  5. "text/template"
  6. )
  7.  
  8. type TemplateData struct {
  9. Name string
  10. }
  11.  
  12. func main() {
  13. funcMap := template.FuncMap{
  14. "ToUpper": strings.ToUpper,}
  15.  
  16. tmpl,_ := template.New("myTemplate").Funcs(funcMap).Parse(string("{{ .Name | ToUpper }}"))
  17.  
  18. templateDate := TemplateData{"Hello"}
  19. var result bytes.Buffer
  20.  
  21. tmpl.Execute(&result,templateDate)
  22. fmt.Println(result.String())
  23. }

猜你在找的Go相关文章