要在 Golang 的 text/template 中定义一个自定义函数可以通过下面代码实现:


import (
    "text/template"
)
// 定义自定义函数
func myFunc(args ...interface{}) interface{} {
    // TODO: 实现自定义函数逻辑
    return nil
}
// 创建模板
t := template.New("mytemplate")
// 注册自定义函数
t = t.Funcs(template.FuncMap{"myFunc": myFunc})
// 解析模板
t, err := t.Parse("{{myFunc .}}")
// 执行模板
err = t.Execute(os.Stdout, "hello world")
myFunctemplate.Newt.Funcst.Parset.Execute

要在模板中定义一个 SQL 查询可以通过下面代码实现:


// 创建模板
t := template.New("mytemplate")
// 定义 SQL 查询
sqlQuery := "SELECT * FROM mytable WHERE name = '{{.}}'"
// 解析模板
t, err := t.Parse(sqlQuery)
// 执行模板
err = t.Execute(os.Stdout, "John")
template.Newt.ParseJohn{{.}}