请教一下: 在下面的一个模板string里面,从一个结构体里面传入一个name字符串变量。 tpl_str := "hello, {{.name}}" tpl_str += " {{.name}} is a machine。"
我想让传入的name变量在第一行所有字母都是大写的,怎么来操作呢?
先谢谢了!
请教一下: 在下面的一个模板string里面,从一个结构体里面传入一个name字符串变量。 tpl_str := "hello, {{.name}}" tpl_str += " {{.name}} is a machine。"
我想让传入的name变量在第一行所有字母都是大写的,怎么来操作呢?
先谢谢了!
我给的链接下面就是 example啊,这个也需要我贴么……
package main
import ( "log" "os" "strings" "text/template" )
func main() { // First we create a FuncMap with which to register the function. funcMap := template.FuncMap{ // The name "title" is what the function will be called in the template text. "title": strings.Title, }
// A simple template definition to test our function.
// We print the input text several ways:
// - the original
// - title-cased
// - title-cased and then printed with %q
// - printed with %q and then title-cased.
const templateText = `
Input: {{printf "%q" .}} Output 0: {{title .}} Output 1: {{title . | printf "%q"}} Output 2: {{printf "%q" . | title}} `
// Create a template, add the function map, and parse the text.
tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
if err != nil {
log.Fatalf("parsing: %s", err)
}
// Run the template to verify the output.
err = tmpl.Execute(os.Stdout, "the go programming language")
if err != nil {
log.Fatalf("execution: %s", err)
}
}
template里可以传入FuncMap,里面是转换函数。
然后在模板里调用转换函数转换