如何向Golang text/template函数传递静态字符串?
问题分析
在Go的text/template中,你直接写入的user_should_share_the_information会被模板引擎当作标识符(变量或函数名)解析,而非静态字符串,所以才会出现“找不到函数”的错误。
解决方法
把静态字符串用双引号包裹,作为字符串字面量传递给模板函数即可。模板解析时会将带引号的内容识别为字符串,而非标识符。
你可以两种方式修改模板:
- 若模板用双引号定义,内部双引号需要转义:
tmpl, err := template.New("info").Funcs(funcs).Parse( "info: {{getStaticStr \"user_should_share_the_information\" }}")
- 用反引号定义模板,内部双引号无需转义,写法更简洁:
tmpl, err := template.New("info").Funcs(funcs).Parse( `info: {{getStaticStr "user_should_share_the_information" }}`)
完整可运行代码
package main import ( "bytes" "fmt" "text/template" ) type people struct { name string age int } // 模拟远程接口返回 func getTextFromUserCenterByKey(val string) string { return "用户应共享信息" } func getStaticStr(val string) string { return getTextFromUserCenterByKey(val) } func main() { funcs := template.FuncMap{ "getStaticStr": getStaticStr, } // 使用反引号定义模板,避免转义 tmpl, err := template.New("info").Funcs(funcs).Parse( `info: {{getStaticStr "user_should_share_the_information" }}`) if err != nil { fmt.Println(err) return } buffer := bytes.Buffer{} _ = tmpl.Execute(&buffer, map[string]interface{}{}) fmt.Println(buffer.String()) }
这样修改后,静态字符串会被正确传递给getStaticStr函数,完全符合你“控制变量定义在模板中,而非传入数据里”的需求。
内容的提问来源于stack exchange,提问作者lanyyyy
相关产品推荐
相关产品推荐

