Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang template : Use pipe to uppercase string

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

like image 958
manuquentin Avatar asked Jan 09 '14 21:01

manuquentin


People also ask

How do you make a string uppercase in Golang?

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.

How do you get the first letter of capital in Golang?

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.

What is go template?

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.


1 Answers

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())
}
like image 119
Nick Craig-Wood Avatar answered Sep 18 '22 08:09

Nick Craig-Wood