man*_*tin 11 string templates go uppercase
我希望在golang模板中使用string.ToUpper
如下大写字符串:
{{ .Name | strings.ToUpper }}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为strings
它不是我数据的属性.
我无法导入strings
包,因为警告我它没有被使用.
Nic*_*ood 37
只需使用像这样的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())
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8952 次 |
最近记录: |