【问题标题】:Golang template : Use pipe to uppercase stringGolang 模板:使用管道转大写字符串
【发布时间】:2014-01-28 15:30:59
【问题描述】:

我想使用 string.ToUpper 将 golang 模板中的字符串大写:

{{ .Name | strings.ToUpper  }}

但这不起作用,因为strings 不是我数据的属性。

我无法导入 strings 包,因为警告我它没有被使用。

这里的脚本: http://play.golang.org/p/7D69Q57WcN

【问题讨论】:

  • 这并不能回答问题,但是:如果您使用此模板呈现 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())
}

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多