2014-01-09 40 views
6

我要大寫使用string.ToUpper像在golang模板的字符串:Golang模板:使用管道大寫串

{{ .Name | strings.ToUpper }} 

但這並不作品,因爲strings是不是我的數據的屬性。

我無法導入strings包,因爲它警告我它沒有使用。

這裏的腳本: http://play.golang.org/p/7D69Q57WcN

+1

這並不回答問題,但是:如果您使用此模板呈現HTML,請考慮大小寫是否只是表示形式。如果是這樣,請使用CSS的'text-transform:capitalize'來代替 - 這甚至是[語言意識](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform)。 – djd

回答

28

只需使用一個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()) 
}