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
Golang String to Uppercase To convert string to upper case in Go programming, call strings. ToUpper() function and pass the string as argument to this function.
Share: If you want to make a title from your string in Go, i.e., make the first letter of each word in the string uppercase, you need to use the cases. Title() function from the golang.org/x/text/cases package. The function creates a language-specific title caser that capitalizes the first letter of each word.
Go's template is designed to be extended by developers, and provides access to data objects and additional functions that are passed into the template engine programmatically. This tutorial only uses functions universally provided in the text/template package, and does not discuss the specifics of data access.
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())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With