18

I want to upper case a string in a golang template using string.ToUpper like :

{{ .Name | strings.ToUpper  }}

But this doesn't works because strings is not a property of my data.

I can't import strings package because the warns me that it's not used.

Here the script : http://play.golang.org/p/7D69Q57WcN

julienc
  • 19,087
  • 17
  • 82
  • 82
manuquentin
  • 894
  • 1
  • 11
  • 19
  • 4
    This doesn't answer the question, but: if you're rendering HTML with this template, have a think about whether the uppercasing is just presentational. If it is, use CSS's `text-transform: capitalize` instead – this is even [language aware](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform). – djd Jan 10 '14 at 02:49

1 Answers1

50

Just use a FuncMap like this (playground) to inject the ToUpper function into your template.

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())
}
Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132