【问题标题】:Golang template : Use pipe to uppercase stringGolang 模板:使用管道转大写字符串
【发布时间】:2014-01-28 15:30:59
【问题描述】:
【问题讨论】:
-
这并不能回答问题,但是:如果您使用此模板呈现 HTML,请考虑大写是否只是表示形式。如果是,请改用 CSS 的 text-transform: capitalize - 这甚至是 language aware。
标签:
string
templates
go
uppercase
【解决方案1】:
只需使用像这样的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())
}