golang 使用 text/template 模板生成代码(备忘)

text/template

text/template 是官方自带的模板生成库

使用例子

package main

import (
	"fmt"
	"os"
	"sort"
	"text/template"
)

var tepl1 = `func (m *{{.ModelName}}) HMapKey() string {
	return fmt.Sprintf("{{.TableName}}:{{.EntityDBID}}:%v", m.{{.EntityID}})
}`

var tepl2 = `
func (m *{{.ModelName}}) PK() (pk string){
	fmtStr:="{{.TableName}}
	{{- range $i, $v := .PKFields -}}
		:%v
	{{- end -}}
	"
	return fmt.Sprintf(fmtStr
		{{- range $i, $v := .PKFields -}}
			, m.{{$v}}
		{{- end -}}
		)
}
`

func main() {

	{
		data := map[string]interface{}{
			"ModelName":  "A",
			"TableName":  "t1",
			"EntityDBID": "id",
			"EntityID":   "ID",
		}
		tmpl, _ := template.New("test").Parse(tepl1)
		tmpl.Execute(os.Stdout, data)
		fmt.Println("")
	}

	{
		data := map[string]interface{}{
			"ModelName": "A",
			"TableName": "t1",
			"PKFields":  sort.StringSlice{"ID", "SubID"},
		}
		tmpl, _ := template.New("test").Parse(tepl2)
		tmpl.Execute(os.Stdout, data)
		fmt.Println("")
	}
}

输出:

func (m *A) HMapKey() string {
        return fmt.Sprintf("t1:id:%v", m.ID)
}

func (m *A) PK() (pk string){
        fmtStr:="t1:%v:%v"
        return fmt.Sprintf(fmtStr, m.ID, m.SubID)
}

你可能感兴趣的:(Go语言杂文,text/template,golang,template,模板生成,自动生成)